SpringBoot 异常之基于 SpringMVC 提供的注解:创建全局异常处理类:通过使用 @ControllerAdvice 定义统一的异常处理类,而不是在每个 Controller 中逐个定义。@ExceptionHandler 用来定义函数针对的异常类型,最后将 Exception 对象和请求 URL 映射到 error.html 中
创建全局异常处理类
- @ControllerAdviceclass GlobalExceptionHandler {
- public static final String DEFAULT_ERROR_VIEW = "error";@ExceptionHandler(value = Exception.class) public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
- ModelAndView mav = new ModelAndView();
- mav.addObject("exception", e);
- mav.addObject("url", req.getRequestURL());
- mav.setViewName(DEFAULT_ERROR_VIEW);
- return mav;
- }
- }
发生异常的 controller
- @RestControllerpublic class IndexController {
- private AtomicInteger atomicInteger = new AtomicInteger();@GetMapping("/index") public String helloWord() {
- throw new IllegalArgumentException("error paramaters");
- }
- }
启动该应用,访问:http://localhost:8080/index,可以看到如下错误提示页面。
通过实现上述内容之后,我们只需要在 Controller 中抛出 Exception,当然我们可能会有多种不同的 Exception。然后在 @ControllerAdvice 类中,根据抛出的具体 Exception 类型匹配 @ExceptionHandler 中配置的异常类型来匹配错误映射和处理
返回 JSON 格式
通过 @ControllerAdvice 统一定义不同 Exception 映射到不同错误处理页面。而当我们要实现 RESTful API 时,返回的错误是 JSON 格式的数据,而不是 HTML 页面,这时候我们也能轻松支持。
本质上,只需在 @ExceptionHandler 之后加入 @ResponseBody,就能让处理函数 return 的内容转换为 JSON 格式。
就爱阅读 www.92to.com 网友整理上传, 为您提供最全的知识大全, 期待您的分享,转载请注明出处。
来源: http://www.92to.com/bangong/2017/04-17/20564262.html