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状态码。

相关推荐
山甫aa1 分钟前
日志技术 Logback + Slf4j —— 从零开始的 Web 后端学习
java·后端·学习·web·logback
韶博雅4 分钟前
开启补充日志
java·开发语言·sql
FYKJ_201013 分钟前
django学习成绩预警系统10905
java·javascript·spring boot·python·spark·django·php
卓怡学长22 分钟前
w192基于springboot教务管理系统
java·数据库·spring boot·spring·maven·intellij-idea
逸Y 仙X26 分钟前
Spark SQL
java·大数据·sql·spark
码农颜27 分钟前
6.4.1 监听连接
java·数据库·mysql
mldong28 分钟前
会签三兄弟:并行/串行/按比例的实现与取舍
java·架构
SomeB1oody1 小时前
【RustyML入门】7.3. 性能调优与并行
开发语言·后端·机器学习·rust·教程
Java后端的Ai之路1 小时前
01、Python - 设计模式介绍
java·人工智能·python·设计模式·通用
zzzll11111 小时前
大模型技术原理与应用实践
java·数据库·人工智能