我想处理正常请求和休息/ajax 请求的异常。这是我的代码,
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(Exception.class)
public ModelAndView handleCustomException(Exception ex) {
ModelAndView model = new ModelAndView("error");
model.addObject("errMsg", ex.getMessage());
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
sw.toString();
model.addObject("errTrace", sw);
return model;
}
@ExceptionHandler(Exception.class)
@ResponseBody
public String handleAjaxException(Exception ex) {
JSONObject model = new JSONObject();
model.put("status", "error");
model.put("errMsg", ex.getMessage());
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
sw.toString();
model.put("errTrace", sw);
return model.toString();
}
}
这会给我一个错误,因为我不能有 @ExceptionHandler(Exception.class) 两次。那么解决方案是什么?
查看@ControllerAdvice的配置:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html
因此,您可以创建两个类(错误处理程序)并指定注释/basePackages/assignibaleTypes
例如,对于 REST(ajax),为控制器使用 @RestController 注释,您可以处理如下错误:
@ControllerAdvice(annotations = RestController.class)
public class MyExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public String handleAjaxException(Exception ex) {
...
}
}
对于其他情况,它可以是带有注释的错误处理程序
@ControllerAdvice(annotations = Controller.class)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)