zoukankan      html  css  js  c++  java
  • Java项目构建基础之统一异常

    统一异常处理

    @ControllerAdvice

    该注解为统一异常处理的核心

    是一种作用于控制层的切面通知(Advice),该注解能够将通用的@ExceptionHandler、@InitBinder和@ModelAttributes方法收集到一个类型,并应用到所有控制器上

    该类中的设计思路:

    • 使用@ExceptionHandler注解捕获指定或自定义的异常;

    • 使用@ControllerAdvice集成@ExceptionHandler的方法到一个类中;

    • 必须定义一个通用的异常捕获方法,便于捕获未定义的异常信息;

    • 自定一个异常类,捕获针对项目或业务的异常;

    • 异常的对象信息补充到统一结果枚举中;

    自定义全局异常类

    @Data
    public class CMSException extends RuntimeException {
        private Integer code;
    
        public CMSException(Integer code, String message) {
            super(message);
            this.code = code;
        }
    
        public CMSException(ResultCodeEnum resultCodeEnum) {
            super(resultCodeEnum.getMessage());
            this.code = resultCodeEnum.getCode();
        }
    
        @Override
        public String toString() {
            return "CMSException{" + "code=" + code + ", message=" + this.getMessage() + '}';
        }
    }

    统一异常处理器

    // ...
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        /**-------- 通用异常处理方法 --------**/
        @ExceptionHandler(Exception.class)
        @ResponseBody
        public R error(Exception e) {
            e.printStackTrace();
            return R.error();    // 通用异常结果
        }
    
        /**-------- 指定异常处理方法 --------**/
        @ExceptionHandler(NullPointerException.class)
        @ResponseBody
        public R error(NullPointerException e) {
            e.printStackTrace();
            return R.setResult(ResultCodeEnum.NULL_POINT);
        }
    
        @ExceptionHandler(HttpClientErrorException.class)
        @ResponseBody
        public R error(IndexOutOfBoundsException e) {
            e.printStackTrace();
            return R.setResult(ResultCodeEnum.HTTP_CLIENT_ERROR);
        }
    
        /**-------- 自定义定异常处理方法 --------**/
        @ExceptionHandler(CMSException.class)
        @ResponseBody
        public R error(CMSException e) {
            e.printStackTrace();
            return R.error().message(e.getMessage()).code(e.getCode());
        }
    }

    控制层展示

    以下为展示当遇到null指定异常时,返回的结果信息

    {
      "success": false,
      "code": 20007,
      "message": "空指针异常",
      "data": {}
    }
    View Code
  • 相关阅读:
    bzoj 1017 魔兽地图DotR
    poj 1322 chocolate
    bzoj 1045 糖果传递
    poj 3067 japan
    timus 1109 Conference(二分图匹配)
    URAL 1205 By the Underground or by Foot?(SPFA)
    URAL 1242 Werewolf(DFS)
    timus 1033 Labyrinth(BFS)
    URAL 1208 Legendary Teams Contest(DFS)
    URAL 1930 Ivan's Car(BFS)
  • 原文地址:https://www.cnblogs.com/gjq1126-web/p/12597687.html
Copyright © 2011-2022 走看看