现在的位置: 首页 > 编程语言 > 正文

SpringBoot逻辑异常统一处理方法

2020年02月13日 编程语言 ⁄ 共 2375字 ⁄ 字号 评论关闭

这篇文章主要介绍了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@ControllerAdvicepublic 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); }}

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: SpringBoot逻辑异常统一处理方法

以上就上有关SpringBoot逻辑异常统一处理方法的全部内容,学步园全面介绍编程技术、操作系统、数据库、web前端技术等内容。

抱歉!评论已关闭.