我想創建一個自定義的業務異常:定製春天例外綁定變量
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 1L;
public BusinessException(String msg) {
super(msg);
}
public BusinessException(String msg, Object[] params) {
//Not sure how to pass params to @ExceptionHandler
super(msg);
}
}
,並在我的Spring MVC的休息控制器使用它:
@RequestMapping(value = "/{code}", method = RequestMethod.GET)
public @ResponseBody
String getState(@PathVariable String code) throws Exception {
String result;
if (code.equals("KL")) {
result = "Kerala";
} else {
throw new BusinessException("NotAValidStateCode",new Object[]{code});
}
return result;
}
我處理所有使用普通的businessException異常處理程序:
@ControllerAdvice
public class RestErrorHandler {
private static final Logger LOGGER = LoggerFactory
.getLogger(RestErrorHandler.class);
@Autowired
private MessageSource messageSource;
@ExceptionHandler(BusinessException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public String handleException(
Exception ex) {
Object[] args=null; // Not sure how do I get the args from custom BusinessException
String message = messageSource.getMessage(ex.getLocalizedMessage(),
args, LocaleContextHolder.getLocale());
LOGGER.debug("Inside Handle Exception:" + message);
return message;
}
}
現在我的問題是,我想從消息中讀取消息文本s屬性文件,其中一些鍵需要運行時綁定變量,例如
NotAValidStateCode= Not a valid state code ({0})
我不知道如何將這些參數傳遞給handleException方法的RestErrorHandler。