springboot学习(五) 全局异常处理

创建全局异常处理

 1 /**
 2  *  全局异常配置管理
 3  */
 4 @ControllerAdvice
 5 public class GlobalExceptionConfig extends ResponseEntityExceptionHandler {
 6 
 7     public static final String DEFAULT_ERROR_VIEW = "error/error";
 8 
 9     @ExceptionHandler(value = Exception.class)
10     public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
11         ModelAndView mav = new ModelAndView();
12         mav.addObject("exception", e);
13         mav.addObject("url", req.getRequestURL());
14         mav.setViewName(DEFAULT_ERROR_VIEW);
15         return mav;
16     }
17 
18     @ExceptionHandler(value = JSONException.class)
19     @ResponseBody
20     public String defaultJsonErrorHandler(HttpServletRequest req, Exception e) throws Exception {
21         return "返回指定格式的数据";
22     }
23 
24     /**
25      *  获取错误的状态码
26      * @param request
27      * @return
28      */
29     private HttpStatus getStatus(HttpServletRequest request) {
30         Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
31         if (statusCode == null) {
32             return HttpStatus.INTERNAL_SERVER_ERROR;
33         }
34         return HttpStatus.valueOf(statusCode);
35     }

  在全局异常类中,设置了2个ExceptionHandler(1个作为页面跳转,一个作为json数据返回),其中的JSONException是我们自己定义的一个异常类,目的就是为了标识这种异常类型返回的数据为json,而不是页面跳转。

posted on 2018-01-20 20:19  程序员AI  阅读(190)  评论(0编辑  收藏  举报

导航