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());
        }
    
    }
  • 相关阅读:
    利用avicap32.dll实现的实时视频传输
    异常错误:在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式
    很不错的python 机器学习资源
    基于C#的机器学习--目录
    C#WinForm无边框窗体移动----模仿鼠标单击标题栏移动窗体位置
    C# WinForm窗体控件GroupBox修改边框颜色控件
    wireshark抓包新手使用教程
    Winform开发框架之权限管理系统功能介绍
    自定义控件开发的调试及DesignMode的状态处理
    Winform开发框架之权限管理系统改进的经验总结(4)--用户分级管理
  • 原文地址:https://www.cnblogs.com/seanRay/p/14985741.html
Copyright © 2011-2022 走看看