Springboot中-全局异常处理类用法示例
使用springboot搭建web项目的时候,一般都会添加一个全局异常类,用来统一处理各种自定义异常信息,
和其他非自定义的异常信息,以便于统一返回错误信息。下面就是简单的示例代码,
自定义异常信息.
public class MyException extends RuntimeException{
private String errorCode = ResultEnum.OTHER_EXCEPTION.getCode();
private String errorMessage ;
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public MyException() {
super();
}
public MyException(String errorCode, String... errorParam) {
super();
setErrorMessage(errorCode, errorParam);
}
private void setErrorMessage(String code, String... param) {
this.errorCode = code;
if (param == null) {
this.errorMessage = "系统异常";
} else if (param.length == 1) {
this.errorMessage = param[0];
} else if (param.length > 1) {
this.errorMessage = "系统异常";
}
}
}
全局异常信息处理类.
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/*
* 处理自定义异常
*/
@ExceptionHandler(value = MyException.class)
public @ResponseBody JsonResult exceptionHandler (MyException myException) {
log.info("exceptionHandler--->{}", myException);
JsonResult jsonResult = new JsonResult();
jsonResult.setErrorCode(myException.getErrorCode());
jsonResult.setErrorMessage(myException.getErrorMessage());
return jsonResult;
}
/*
* 处理参数校验异常-1
* */
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public @ResponseBody JsonResult methodArgumentNotValidExceptionHandler (MethodArgumentNotValidException mANValidException) {
log.info("参数校验异常1!");
JsonResult jsonResult = new JsonResult();
jsonResult.setErrorCode(ResultEnum.PARAMS_ERROE.getCode());
// 获取所有的校验错误信息
List<ObjectError> allErrors = mANValidException.getBindingResult().getAllErrors();
StringBuilder sb = new StringBuilder();
// 处理错误的校验信息
if (allErrors != null && allErrors.size() > 1) {
allErrors.forEach(item->sb.append(item.getDefaultMessage()).append("#"));
} else {
allErrors.forEach(item->sb.append(item.getDefaultMessage()));
}
jsonResult.setErrorMessage(sb.toString());
return jsonResult;
}
/*
* 处理系统异常
* */
@ExceptionHandler(value = Exception.class)
public @ResponseBody JsonResult constraintViolationExceptionHandler (Exception exception) {
log.info("exception--->{}", exception);
JsonResult jsonResult = new JsonResult();
jsonResult.setErrorCode(ResultEnum.SYSTEM_EXCEPTION.getCode());
jsonResult.setErrorMessage(ResultEnum.SYSTEM_EXCEPTION.getMsg());
return jsonResult;
}
}
返回信息处理类.
@Data
public class JsonResult<T> implements Serializable {
private static final long serialVersionUID = -7866290240453139258L;
//返回时间
private String responseDate = null;
//返回状态
private String status = null;
//错误码
private String errorCode = null;
//错误信息
private String errorMessage = null;
//接口返回对象
private T responseBody = null;
public JsonResult() {
this.status = "SUCCESS";
this.responseDate = (new Date()).toString();
}
public JsonResult(T responseBody) {
this();
this.status = "SUCCESS";
this.responseBody = responseBody;
this.errorCode = "";
this.errorMessage = "";
}
public JsonResult<T> declareSuccess(T responseBody) {
this.status = "SUCCESS";
this.responseBody = responseBody;
this.errorCode = "";
this.errorMessage = "";
return this;
}
public JsonResult<T> declareFailure(MyException e, T responseBody) {
return declareFailure(e.getMessage(), e.getMessage(), responseBody);
}
public JsonResult<T> declareFailure(String errorCode, String errorMessage, T responseBody) {
this.status = "FAILURE";
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.responseBody = responseBody;
return this;
}
}
错误信息返回的枚举类.
public enum ResultEnum {
SUCCESS("1000", "成功"),
FAILED("1001", "失败"),
PARAMS_ERROE("1002", "参数错误"),
OTHER_EXCEPTION("1003", "其他错误"),
SYSTEM_EXCEPTION("0000", "系统异常"),
;
/*
* 返回码
*/
private String code;
/*
* 返回消息
*/
private String msg;
ResultEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
测试的controller如下
@Slf4j
@RestController
public class TestControlelr {
@Autowired
private TestMapper testMapper;
@PostMapping("/exception/test")
public JsonResult exceptionTest(@Validated @RequestBody ParamTest paramTest){
TestPO testPO = new TestPO();
testPO.setNewTable("app_goods_info");
int total = testMapper.selectTotal(testPO);
System.out.println("total--->" + total);
JsonResult jsonResult = new JsonResult();
jsonResult.declareSuccess("异常测试接口:" + total);
return jsonResult;
}
@GetMapping("/exception/test/two")
public JsonResult exceptionTestTwo(){
int total = 10;
System.out.println("total--->" + total);
int temp = 1 / 0;
JsonResult jsonResult = new JsonResult();
jsonResult.declareSuccess("异常测试接口:" + total);
return jsonResult;
}
@PostMapping("/exception/test/three")
public JsonResult exceptionTestThree(){
int total = 10;
System.out.println("total--->" + total);
if (total > 8) {
throw new MyException(ResultEnum.FAILED.getCode(), "测试自定义异常");
}
JsonResult jsonResult = new JsonResult();
jsonResult.declareSuccess("异常测试接口:" + total);
return jsonResult;
}
}
测试的入参类如下:
@Data
public class ParamTest {
/*
* 名称
*/
@NotNull(message = "名称不能为null")
private String name;
/*
* 简介
*/
@Length(max = 10, message = "简介长度最大为10")
private String abs;
}
测试一:填写错误的参数,返回信息如下。
测试二:测试在代码中写1/0的返回结果。

测试三:主动抛出一个自定义异常,返回结果如下。
在全局异常处理类中添加了三个方法,一个方法用来处理自定义异常的错误返回信息,一个方法用法用来返回参数校验的错误返回信息,
最后一个方法用来处理系统异常,三个方法都可以正常执行。真实开发中可以根据实际需要去添加一些自定义
异常信息,根据需要使用全局异常类来进行统一处理,这样可以很方便的从错误信息中分辨出是什么地方出现问题,便于快速排查问题。
Springboot中-全局异常处理类用法示例的更多相关文章
- springboot的全局异常处理类
import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import or ...
- 【springboot】全局异常处理
转自: https://blog.csdn.net/cp026la/article/details/86495196 前言: 开发中异常的处理必不可少,常用的就是 throw 和 try catch, ...
- SpringMVC的处理器全局异常处理类
SpringMVC的处理器全局异常处理类 package com.huawei.utils; import org.springframework.web.servlet.HandlerExcepti ...
- springBoot的全局异常处理
GlobalException.java package com.bank.util; import com.bank.exception.ContentEmpyException; import c ...
- SpringBoot中对于异常处理的提供的五种处理方式
1.自定义错误页面 SpringBoot 默认的处理异常机制:SpringBoot默认的已经提供了一套处理异常的机制.一旦程序中出现了异常,SpringBoot会向/error的url发送请求.在Sp ...
- springmvc、 springboot 项目全局异常处理
异常在项目中那是不可避免的,通常情况下,我们需要对全局异常进行处理,下面介绍两种比较常用的情况. 准备工作: 在捕获到异常的时候,我们通常需要返回给前端错误码,错误信息等,所以我们需要手动封装一个js ...
- SpringBoot中SpringMVC异常处理机制
声明 源码基于SpringBoot 2.3.12 前置知识 Tomcat异常处理机制 使用例子 原理简要介绍 先来看下Spring Boot中默认的处理行为,如果DispatcherServlet执行 ...
- SpringBoot整合全局异常处理&SpringBoot整合定时任务Task&SpringBoot整合异步任务
============整合全局异常=========== 1.整合web访问的全局异常 如果不做全局异常处理直接访问如果报错,页面会报错500错误,对于界面的显示非常不友好,因此需要做处理. 全局异 ...
- SpringBoot中的异常处理方式
SpringBoot中有五种处理异常的方式: 一.自定义错误页面 SpringBoot默认的处理异常机制:SpringBoot默认的已经提供了一套处理异常的机制.一旦程序出现了异常SpringBoot ...
- C#中this指针的用法示例
这篇文章主要介绍了C#中this指针的用法,对初学者而言是非常重要的概念,必须加以熟练掌握,需要的朋友可以参考下. 本文实例展示了C#中this指针的用法,对于初学者进一步牢固掌握C#有很大帮助,具体 ...
随机推荐
- go中string是如何实现的呢
go中string是如何实现的呢 前言 实现 go语言中的string是不可变的 []byte转string string转[]byte 字符串的拼接 +方式进行拼接 fmt 拼接 Join 拼接 b ...
- Django后台输出原生SQL语句
如果需要打印orm翻译后的原生sql语句,只需要在setting最后加上下面代码就行. 1 LOGGING = { 2 'version': 1, 3 'disable_existing_logger ...
- 记录一则ADG备库报错ORA-29771的案例
有客户找到我这边咨询,说他们的一套核心ADG库在业务高峰期报错,因为业务做了读写分离,其备库也实际承担读业务,所以备库故障也会对业务产生影响. 这里也要提醒大家,做读写分离,如果读库出现故障的情况,要 ...
- Docker生命周期,一张图秒懂docker
- Pandas 人口密度案例分析
from turtle import left import pandas as pd """ 需求: 1.导入文件,查看原始数据 2.将人口数据和各州简称数据进行合并 ...
- pip指定镜像安装
清华大学开源软件镜像站
- OGP协议的使用
OGP协议是一套Metatags的规格,用来标注页面,告诉我们你的网页快照.帮助社交app高效并准确的获取网页中的核心链接.标题.主图.正文摘要等信息,使得该网页在社交分享中有更好的展现体验. 如果网 ...
- 发布Npm包到GitHub Packages
发布Npm包到GitHub Packages Github集成了GitHub Packages功能,目前提供了Npm.Docker.Maven.NuGet.RubyGems的包管理工具,可以通过Git ...
- js加css实现div展示更多隐藏内容
说明 在设计博客首页文章分类等栏目时,有时候列表内容太多往往不是一次性展示出来.此时需要添加更多功能,当点击更多标签时再展示剩余隐藏的项目. 效果 代码 <!DOCTYPE html> & ...
- Spring源码之bean的加载
目录 1. FactoryBean 的使用 2. 缓存中获取单例 bean: 3. 从 bean 实例获取对象, 4. 获取单例 bean (从缓存加载失败): 5. 创建 bean (createB ...

