@ExceptionHandler指定需要处理的异常类,针对自定义异常,如果是ajax请求,返回json信息,如果是普通web请求,返回ModelAndView对象。
/** * 全局异常处理器 * @author Summerday */ @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(CustomException.class) public Object handle(HttpServletRequest request, CustomException e) { AjaxResult info = AjaxResult.error(e.getMessage()); log.error(e.getMessage()); // 判断是否为ajax请求 if (isAjaxRequest(request)) { return info; } ModelAndView mv = new ModelAndView(); mv.setViewName("custom"); // templates/custom.html mv.addAllObjects(info); mv.addObject("url", request.getRequestURL()); return mv; } private boolean isAjaxRequest(HttpServletRequest request) { return "XMLHttpRequest".equals(request.getHeader("X-Requested-With")); } }在Controller层,人为定义抛出异常:
@RestController public class TestController { @GetMapping("/ajax") public AjaxResult ajax() { double alpha = 0.9; if (Math.random() < alpha) { throw new CustomException("自定义异常!"); } return AjaxResult.ok(); } }最后,通过/templates/custom.html定义的动态模板页面展示数据:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>自定义界面</title> </head> <body> <p th:text="'msg -->'+ ${msg}"></p> <p th:text="'code -->'+ ${code}"></p> <p th:text="'url -->'+ ${url}"></p> </body> </html> 源码下载本文内容均为对优秀博客及官方文档总结而得,原文地址均已在文中参考阅读处标注。最后,文中的代码样例已经全部上传至Gitee:https://gitee.com/tqbx/springboot-samples-learn。