zoukankan      html  css  js  c++  java
  • 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());
        }
    
    }
  • 相关阅读:
    百度富文本编辑器的上传图片的路径问题
    laravel初次学习总结及一些细节
    macOS apache配置及开启虚拟服务器的开启,apache开启重写模式
    类似于qq空间类型的评论和回复
    向php提交数据及json
    mac 初次配置apache,及mac下安装mysql
    C#连接mysql数据库插入数据后获取自增长主键ID值
    PHP 真正多线程的使用
    C# 连接mysql数据库
    MySql状态查看方法 MySql如何查看连接数和状态?
  • 原文地址:https://www.cnblogs.com/seanRay/p/14985741.html
Copyright © 2011-2022 走看看