SpringBoot逻辑异常统一处理方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot逻辑异常统一处理方法

  2021-04-02 我要评论

这篇文章主要介绍了SpringBoot逻辑异常统一处理方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

构建项目

我们将逻辑异常核心处理部分提取出来作为单独的jar供其他模块引用,创建项目在parent项目pom.xml添加公共使用的依赖,配置内容如下所示:

<dependencies>
    <!--Lombok-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <!--测试模块依赖-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <!--web依赖-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

项目创建完成后除了.idea、iml、pom.xml保留,其他的都删除。

异常处理核心子模块

/**
 * @author WGR
 * @create 2019/9/7 -- 15:06
 */
public class OssException extends RuntimeException implements Serializable {
  private static final long serialVersionUID = 1L;
  private Object[] errFormatArr;
  public OssException(String message,Object... obj) {
    super(message);
    this.errFormatArr = obj;
  }
  //由于实际需要,因此又追加以下两种构造方法
  public OssException(String message, Throwable cause) {
    super(message, cause);
  }
  public OssException(Throwable cause) {
    super(cause);
  }
  public Object[] getErrFormatArr() {
    return errFormatArr;
  }
  public void setErrFormatArr(Object[] errFormatArr) {
    this.errFormatArr = errFormatArr;
  }
}

统一返回结果定义

@Slf4j
@ControllerAdvice
public class OssExceptionHandler {
​
  @ExceptionHandler(value = Exception.class)
  @ResponseBody
  public ModelAndView handle(Exception ex) {
    //使用FastJson提供的FastJsonJsonView视图返回,不需要捕获异常
    FastJsonJsonView view = new FastJsonJsonView();
​
    R result = null;
    if (ex instanceof OssException) {//自义异常
      result = M.getErrR(ex.getMessage(),((OssException) ex).getErrFormatArr());
    }else if(ex instanceof MaxUploadSizeExceededException) {//Spring的文件上传大小异常
      result = M.getErrR("exception.maxUploadSizeExceededException",PropUtil.getInteger("upload.maxSize"));
    }else if(ex instanceof DataAccessException) {//Spring的JDBC异常
      result = M.getErrR("exception.dataAccessException");
    }else {//其他未知异常
      result = M.keyErrR("exception.other");
    }
​
    //开发过程中打印一下异常信息,生产过程可关闭
    if(result.getErrCode() != 60113) { //20181225 登陆会话失效,不打印了
      String stackTrace = StackUtil.getStackTrace(ex);
      log.error("----->"+stackTrace);
    }
​
​
    //电脑端,封装异常信息 20181128 安全测试问题要求关闭详细异常信息
    //if(WebUtil.isComputer()) result.setErrdetail(stackTrace);
    result.setErrdetail(ex.getMessage()); //20190128 异常信息简易的还需加入
    view.setAttributesMap(result);
​
    return new ModelAndView(view);
  }
}

由于种种原因,只能贴出部分代码,可以提供思路。

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们