统一异常处理

367 阅读1分钟

定义自定义异常类 继承 RuntimeException 运行时异常(不受检查,运行期才可以发现的异常),抛出友好提示给前端。

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class GuliException extends RuntimeException {
        @ApiModelProperty(value = "状态码")
        private Integer code;
        @ApiModelProperty(value = "异常信息提示")
        private String message;
    }

统一异常处理类 处理异常,使用注解 @ControllerAdvice 统一捕获(系统或者手动抛出的异常)异常,进行统一处理。

    @ControllerAdvice // spring IOC AOP
    public class GlobalExceptionHandler {

        @ExceptionHandler(Exception.class) // 当出现运行时异常时   系统自动抛
        @ResponseBody
        public MsgResult ww(Exception e){
            e.printStackTrace();
            return MsgResult.error();
        }

        // 特殊异常处理   ArithmeticException 计算异常
        @ExceptionHandler(ArithmeticException.class) // 当出现运行时异常时  自动抛
        @ResponseBody
        public MsgResult ts(ArithmeticException e){
            e.printStackTrace();
            return MsgResult.error().message("计算异常");
        }

        // 自定义异常时   需要 try catch  throws 手动抛,系统捕获此异常 返回前端 错误提示
        @ExceptionHandler(GuliException.class)
        @ResponseBody
        public MsgResult zdy(GuliException e){
            e.printStackTrace();
            return MsgResult.error().message(e.getMessage()).code(e.getCode());
        } 
    }

对于自定义异常 两种方式 1: try catch 抛出 eg: 调用其他比如第三方服务,捕获其异常 进行抛出。

image.png

2:根据自身业务逻辑 主动抛出

image.png

补充: 状态码定义:

image.png

统一返回前端消息封装:

@Data
public class MsgResult {

   @ApiModelProperty(value = "是否成功")
   private Boolean success;

   @ApiModelProperty(value = "标志码")
   private Integer code;

   @ApiModelProperty(value = "消息提示")
   private String message;

   @ApiModelProperty(value = "返回数据")
   private Map<String, Object> data = new HashMap<String, Object>();

   private MsgResult(){}

   public static MsgResult ok(){
       MsgResult r = new MsgResult();
       r.setSuccess(true);
       r.setCode(ResultCode.SUCCESS);
       r.setMessage("成功");
       return r;
   }

   public static MsgResult error(){
       MsgResult r = new MsgResult();
       r.setSuccess(false);
       r.setCode(ResultCode.ERROR);
       r.setMessage("失败");
       return r;
   }

   public MsgResult success(Boolean success){
       this.setSuccess(success);
       return this;
   }

   public MsgResult message(String message){
       this.setMessage(message);
       return this;
   }

   public MsgResult code(Integer code){
       this.setCode(code);
       return this;
   }

   public MsgResult data(String key, Object value){
       this.data.put(key, value);
       return this;
   }
   public MsgResult data(Map<String,Object> map){
       this.setData(map);
       return this;
   }


}