SpringBoot优雅的全局异常处理

SpringBoot优雅的全局异常处理

  • 导入依赖

    <!--fastjson-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.41</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    
  • 自定义数据格式

    后台返回统一数据格式

    //保证序列化Json的时候,如果是null的对象,key也会消失
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public class ResponseResult<T> implements Serializable{
        private int status;
    
        private String msg;
    
        private  T data;
    
        private ResponseResult(int status)
        {
            this.status = status;
        }
        private ResponseResult(int status, T data)
        {
            this.status = status;
            this.data = data;
        }
        private ResponseResult(int status, String msg, T data)
        {
            this.status = status;
            this.msg = msg;
            this.data = data;
        }
        private ResponseResult(int status, String msg)
        {
            this.status = status;
            this.msg = msg;
        }
    
    
        public int getStatus() {
            return status;
        }
    
        //使之不在json序列化结果当中
        @JsonIgnore
        public Boolean isSuccess()
        {
            return this.status == ResponseCode.SUCCESS.getCode();
        }
    
        public String getMsg() {
            return msg;
        }
    
        public T getData() {
            return data;
        }
    
        public static <T> ResponseResult<T> createBySuccess()
        {
            return  new ResponseResult<T>(ResponseCode.SUCCESS.getCode());
        }
    
        public static <T> ResponseResult<T> createBySuccessMessage(String msg)
        {
            return new ResponseResult<T>(ResponseCode.SUCCESS.getCode(),msg);
        }
    
        public static <T> ResponseResult<T> createBySuccess(T data)
        {
            return new ResponseResult<T>(ResponseCode.SUCCESS.getCode(),data);
        }
    
        public static <T> ResponseResult<T> createBySuccess(String msg, T data)
        {
            return  new ResponseResult<T>(ResponseCode.SUCCESS.getCode(),msg,data);
        }
        /******************errorMsg************************/
    
        public static <T> ResponseResult<T> createByError()
        {
            return  new ResponseResult<T>(ResponseCode.SUCCESS.getCode(),ResponseCode.ERROR.getDesc());
        }
        public static <T> ResponseResult<T> createByErrorMessage(String errorMsg)
        {
            return new ResponseResult<T>(ResponseCode.ERROR.getCode(),errorMsg);
        }
        public static <T> ResponseResult<T> createByErrorMessage(int errorCode, String errorMessage)
        {
            return new ResponseResult<T>(errorCode,errorMessage);
        }
    
    }
    
    
  • 自定义枚举类

    统一定义返回数据的格式中的code和message的值

    public enum  ResponseCode {
      
        NEED_LOGIN(10,"NEED LOGIN"),
        ILLEGAL_ARGUMENT(2,"ILLEGAL ARGUMENT"),
        SUCCESS(200, "成功!"),
        BODY_NOT_MATCH(400,"请求的数据格式不符!"),
        SIGNATURE_NOT_MATCH(401,"请求的数字签名不匹配!"),
        NOT_FOUND(404, "未找到该资源!"),
        INTERNAL_SERVER_ERROR(500, "服务器内部错误!"),
        SERVER_BUSY(503,"服务器正忙,请稍后再试!");
    
        private final String desc;
        private final int code;
    
        ResponseCode(int code,String desc){
            this.code = code;
            this.desc = desc;
        }
    
        public String getDesc() {
            return desc;
        }
    
        public int getCode() {
            return code;
        }
    }
    
  • 自定义异常类

    @Data
    public class BizException extends  RuntimeException {
    
        private static final Long serialVersionUID = 1L;
    
        /**
         * 错误码
         */
        private int errorCode;
    
        /**
         * 错误信息
         */
        private String errorMessage;
    
        public BizException(String errorMessage) {
            super(errorMessage);
            this.errorMessage = errorMessage;
        }
    
        public BizException(String errorMessage, Throwable cause) {
            super(errorMessage, cause);
            this.errorMessage = errorMessage;
        }
    
        public BizException(int errorCode, String errorMessage) {
            super(errorMessage);
            this.errorMessage = errorMessage;
            this.errorCode = errorCode;
        }
    
        public BizException(int errorCode, String errorMessage, Throwable cause) {
            super(errorMessage,cause);
            this.errorMessage = errorMessage;
            this.errorCode = errorCode;
        }
    }
    
  • 全局异常处理类

    @RestControllerAdvice
    @Slf4j
    public class GlobalExceptionHandler {
    
        @ExceptionHandler(BizException.class)
        public ResponseResult handleBizException(BizException e)
        {
           return ResponseResult.createByErrorMessage(e.getErrorCode(),e.getErrorMessage());
        }
    
        /**
         * 处理其他异常
         * @param req
         * @param e
         * @return
         */
        @ExceptionHandler(value =Exception.class)
        @ResponseBody
        public ResponseResult exceptionHandler(HttpServletRequest req, Exception e) {
            log.error("未知异常!原因是:", e);
            return ResponseResult.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getDesc());
    
        }
    }
    

测试

@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping("/login")
    public void login()
    {
        throw new BizException(ResponseCode.INTERNAL_SERVER_ERROR.getCode(),ResponseCode.INTERNAL_SERVER_ERROR.getDesc());
    }

}
posted @ 2021-07-08 13:54  肖恩雷  阅读(140)  评论(0编辑  收藏  举报