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>

项目创建完成后除了.ideaimlpom.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);
    }
​
​
​
}

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

猜你喜欢

转载自www.cnblogs.com/dalianpai/p/11756148.html