我有现有的REST API(使用Spring MVC),只要发生异常,就会返回setInvalid(true)
的默认响应对象。目前,有很多尝试捕获。
我想使用@ExceptionHandler重写它,但在这种情况下我无法猜测我应该返回哪种类型(从单个类继承不同的响应类)。我看到有HandlerMethod类允许我做我想要的但我找不到在异常处理程序中访问它的方法。
有没有办法实现这种一般行为?
答案 0 :(得分:0)
如果要将某些数据从控制器传递到@ExceptionHandler
,那么应该使用带有message参数的constructer来抛出异常。
E.g
catch(Exception e){
if (ex instanceof NullPointerException) {
throw new ABCException("Input is incorrect, Please provide proper input.");
}
}
并在异常处理程序区域中
@ExceptionHandler(ABCException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
String handleExceptions(ABCException re) {
log(re.toString());
return re.getMessage();
}
否则,如果您的想法是根据原点创建自己的消息,那么您可以从Referer获取原点,例如
@ExceptionHandler(ABCException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
String handleExceptions(ABCException re, HttpServletRequest request) {
log(request.getHeader("Referer"););
return something;
}