spring boot 统一异常处理

在Spring Boot中,可以使用@ControllerAdvice注解创建一个全局异常处理类,来处理应用程序中发生的各种异常。以下是一个简单的例子:

import org.springframework.http.HttpStatus;

import org.springframework.web.bind.MethodArgumentNotValidException;

import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.bind.annotation.ResponseStatus;

import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice

public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(Exception.class)

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)

public String handleAllExceptions(Exception ex) {

// 记录日志,处理其他逻辑

return "An error occurred: " + ex.getMessage();

}

@Override

protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,

HttpHeaders headers,

HttpStatus status,

WebRequest request) {

// 记录日志,处理其他逻辑

return new ResponseEntity<>("Validation failed: " + ex.getBindingResult().toString(), HttpStatus.BAD_REQUEST);

}

// 可以添加更多的异常处理方法

}

在这个例子中,我们定义了两个异常处理方法:

1.handleAllExceptions 处理所有类型的异常。

2.handleMethodArgumentNotValid 处理MethodArgumentNotValidException异常,这通常是由于@Valid注解验证失败触发的。

你可以根据需要添加更多的异常处理方法,以处理不同类型的异常。记得在方法上使用@ExceptionHandler注解来指定需要处理的异常类型,并使用@ResponseStatus注解来指定返回的HTTP状态码。

相关推荐
迪飞特科技几秒前
智慧物业平台实战:Spring Boot 整合小程序实现报修巡检费用全流程
spring boot·后端·小程序
考虑考虑5 分钟前
@JsonInclude注解使用
spring boot·后端·spring
Wang's Blog10 分钟前
Java 项目实战: 交友项目 - Dubbo 的内部结构与一次调用的完整链路
java·dubbo
Wang's Blog14 分钟前
Java 项目实战: 交友项目 - Dubbo 入门引导
java·dubbo·交友
IT_陈寒36 分钟前
Vite的这个问题坑了我三天,原来如此解决!
前端·人工智能·后端
网易云信37 分钟前
大模型能上岗做销售吗?我们让 12 款国产模型交了 420 份作业
前端·后端
CCblandy38 分钟前
HTTP 长连接 3 类故障实测:[WinError 10053]、99 个 TIME_WAIT、69 次多余握手,4 种对策怎么选
后端·python·网络协议·http·云原生·性能优化·架构
蜗牛互联网1 小时前
Python Agent工具调用的白名单、参数校验与审批门禁
java·服务器·前端·人工智能·后端·python
SL_staff1 小时前
当规则引擎开始‘懂业务’:JVS-Rules金融风控四大原生能力拆解
java·python·全栈
Shaoshing1 小时前
前缀和与差分
java·数据结构·算法·前缀和·差分