本篇文章为大家展示了如何在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);
}
}
springboot一种全新的编程规范,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,SpringBoot也是一个服务于框架的框架,服务范围是简化配置文件。
上述内容就是如何在SpringBoot中统一处理逻辑异常,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。