使用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中-全局异常处理类用法示例的更多相关文章

  1. springboot的全局异常处理类

    import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import or ...

  2. 【springboot】全局异常处理

    转自: https://blog.csdn.net/cp026la/article/details/86495196 前言: 开发中异常的处理必不可少,常用的就是 throw 和 try catch, ...

  3. SpringMVC的处理器全局异常处理类

    SpringMVC的处理器全局异常处理类 package com.huawei.utils; import org.springframework.web.servlet.HandlerExcepti ...

  4. springBoot的全局异常处理

    GlobalException.java package com.bank.util; import com.bank.exception.ContentEmpyException; import c ...

  5. SpringBoot中对于异常处理的提供的五种处理方式

    1.自定义错误页面 SpringBoot 默认的处理异常机制:SpringBoot默认的已经提供了一套处理异常的机制.一旦程序中出现了异常,SpringBoot会向/error的url发送请求.在Sp ...

  6. springmvc、 springboot 项目全局异常处理

    异常在项目中那是不可避免的,通常情况下,我们需要对全局异常进行处理,下面介绍两种比较常用的情况. 准备工作: 在捕获到异常的时候,我们通常需要返回给前端错误码,错误信息等,所以我们需要手动封装一个js ...

  7. SpringBoot中SpringMVC异常处理机制

    声明 源码基于SpringBoot 2.3.12 前置知识 Tomcat异常处理机制 使用例子 原理简要介绍 先来看下Spring Boot中默认的处理行为,如果DispatcherServlet执行 ...

  8. SpringBoot整合全局异常处理&SpringBoot整合定时任务Task&SpringBoot整合异步任务

    ============整合全局异常=========== 1.整合web访问的全局异常 如果不做全局异常处理直接访问如果报错,页面会报错500错误,对于界面的显示非常不友好,因此需要做处理. 全局异 ...

  9. SpringBoot中的异常处理方式

    SpringBoot中有五种处理异常的方式: 一.自定义错误页面 SpringBoot默认的处理异常机制:SpringBoot默认的已经提供了一套处理异常的机制.一旦程序出现了异常SpringBoot ...

  10. C#中this指针的用法示例

    这篇文章主要介绍了C#中this指针的用法,对初学者而言是非常重要的概念,必须加以熟练掌握,需要的朋友可以参考下. 本文实例展示了C#中this指针的用法,对于初学者进一步牢固掌握C#有很大帮助,具体 ...

随机推荐

  1. 【Mysql】复合主键的索引

    复合主键在where中使用查询的时候到底走不走索引呢?例如下表: create table index_test ( a int not null, b int not null, c int not ...

  2. 【九】强化学习之TD3算法四轴飞行器仿真---PaddlePaddlle【PARL】框架

    相关文章: [一]飞桨paddle[GPU.CPU]安装以及环境配置+python入门教学 [二]-Parl基础命令 [三]-Notebook.&pdb.ipdb 调试 [四]-强化学习入门简 ...

  3. C/C++ 实现枚举网上邻居信息

    在Windows系统中,通过网络邻居可以方便地查看本地网络中的共享资源和计算机.通过使用Windows API中的一些网络相关函数,我们可以实现枚举网络邻居信息的功能,获取连接到本地网络的其他计算机的 ...

  4. C/C++ 通过CRC32实现反破解

    我们可以通过使用CRC32算法计算出程序的CRC字节,并将其写入到PE文件的空缺位置,这样当程序再次运行时,来检测这个标志,是否与计算出来的标志一致,来决定是否运行程序,一旦程序被打补丁,其crc32 ...

  5. 从嘉手札<2023-10-30 >

    杂诗 壬戌辛酉日夜,闲看日月,秋风萧瑟,感怀予身期年孑然,岁月难留,故有所感,藉以此诗. 闲来无事,细数春秋. 初月难盈,残烛易收. 未若知人意,夜夜息绝游. 红叶醉天水,星河绕满楼. 竹影戚戚乱,岁 ...

  6. ajax中的同步异步和跨域请求

    ajax中的同步异步和跨域请求 同步异步 demo.html <script> $.ajax({ type: "get", async: false, data: &q ...

  7. CF1921F Sum of Progression 题解

    题目链接:CF 或者 洛谷 一道经典的类型题,把这种类型的题拿出来单独说一下. 注意到问题中涉及到需要维护 \(a_{x+k\times step}\) 这样的信息,这样的信息很难用树型结构维护,比较 ...

  8. 【奶奶看了也不会】AI绘画 Mac安装stable-diffusion-webui绘制AI妹子保姆级教程

    1.作品图 2.准备工作 目前网上能搜到的stable-diffusion-webui的安装教程都是Window和Mac M1芯片的,而对于因特尔芯片的文章少之又少,这就导致我们还在用老Intel 芯 ...

  9. SpringBoot实现统一异常处理

    目录 前言 实现步骤 定义统一响应对象类 定义业务异常枚举接口和实现 定义业务异常基类 定义全局异常处理切面 测试和验证 总结 前言 近日心血来潮想做一个开源项目,目标是做一款可以适配多端.功能完备的 ...

  10. SpringBoot-MyBatis - Java枚举类型 <---> MySQL Int,建立 类型处理器(typeHandlers)

    场景: MySQL里的某一个字段,比如:status状态,一共有5个状态,我们会在MySQL里 建立 status(int)字段,1.2.3.4.5 来标记5种状态:利用MyBatis在自动代码生成器 ...