zoukankan      html  css  js  c++  java
  • 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,而不是页面跳转。

  • 相关阅读:
    yii2 批量插入
    yii2 ArrayHelper的19个函数+使用实例+功能详解
    thinkphp phpexcel
    yii2 ActiveForm beforeSubmit用法
    YII2项目常用技能知识总结
    Redis 的 fields 遇到的问题
    spring boot +mybatis+druid 多数据源配置
    简单使用shell 自动打包,发布项目 脚本
    cmpp 短信平台
    mysql workbench 导出表结构
  • 原文地址:https://www.cnblogs.com/origalom/p/7587950.html
Copyright © 2011-2022 走看看