SpringBoot逻辑异常统一处理方法

网友投稿 358 2023-07-15

SpringBoot逻辑异常统一处理方法

SpringBoot逻辑异常统一处理方法

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

构建项目

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

org.projectlombok

lombok

true

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-starter-web

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

异常处理核心子模块

/**

* @author WGR

* @create 2019/9/7 -- 15:06

*/

public class OssException extends RuntimeException implements Serializable {http://

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);

http:// log.error("----->"+stackTrace);

}

//电脑端,封装异常信息 20181128 安全测试问题要求关闭详细异常信息

//if(WebUtil.isComputer()) result.seaoxTdnyeKOtErrdetail(stackTrace);

result.setErrdetail(ex.getMessage()); //20190128 异常信息简易的还需加入

view.setAttributesMap(result);

return new ModelAndView(view);

}

}

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:SpringBoot实现接口数据的加解密功能
下一篇:使用Servlet Filter实现系统登录权限
相关文章

 发表评论

暂时没有评论,来抢沙发吧~