我想创建一个自定义业务异常:
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;
}
我正在使用通用异常处理程序处理所有业务异常:
@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;
}
}
现在我的问题是,我想从消息属性文件中读取消息文本,其中一些键需要运行时绑定变量,例如
NotAValidStateCode= Not a valid state code ({0})
我不确定如何将这些参数传递给 RestErrorHandler 的 handleException 方法。