@ControllerAdvice注解,可以对Controller中被 @RequestMapping注解的方法加一些逻辑处理。最常用的就是异常处理。
具体使用
1、定义异常处理类,可以返回json格式数据或者跳转到错误页面
返回json数据:
@ControllerAdvice
public class CustomExceptionHandler {
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Map errorHandler(Exception e) {
Map map = new HashMap();
map.put("code", 400);
//根据异常类型返回信息
if(e instanceof MyException){
map.put("msg","这是自定义异常");
}
return map;
}
}
或者返回页面
@ExceptionHandler(value = MyException.class)
public ModelAndView myErrorHandler(MyException e) {
ModelAndView modelAndView = new ModelAndView();
//指定错误页面的模板页
modelAndView.setViewName("error");
modelAndView.addObject("code", e.getCode());
modelAndView.addObject("msg", e.getMsg());
return modelAndView;
}
2、自定义异常类
//自定义异常类
@Data
public class MyException extends RuntimeException {
private long code;
private String msg;
public MyException(Long code, String msg){
super(msg);
this.code = code;
this.msg = msg;
}
public MyException(String msg){
super(msg);
this.msg = msg;
}
}
项目中的具体使用,记录异常信息,浏览器相应错误信息或者跳转到错误页面:
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {
private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
@ExceptionHandler({Exception.class})
public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
logger.error("服务器发生异常: " + e.getMessage());
for (StackTraceElement element : e.getStackTrace()) {
logger.error(element.toString());
}
//requestedWith为null,则为同步请求;requestedWith为XMLHttpRequest,则为Ajax请求
String xRequestedWith = request.getHeader("x-requested-with");
if ("XMLHttpRequest".equals(xRequestedWith)) {
response.setContentType("application/plain;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.write(CommunityUtil.getJSONString(1, "服务器异常!"));
} else {
//重定向到错误页面
response.sendRedirect(request.getContextPath() + "/error");
}
}
}