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

相关推荐
橘色的喵6 分钟前
ARM-Linux 嵌入式库:内存池与信号量的无锁化改造
后端
SamDeepThinking8 分钟前
写代码,到底应该参考优秀作品,还是坚持自己的想法?
后端
wear工程师8 分钟前
Kafka 消费者心跳正常,为什么还会被踢出组?拆清 max.poll.interval.ms
java·kafka
cfm_291410 分钟前
基于OAuth2.0实现微服务SSO单点登录
后端·spring·微服务·架构
橘色的喵10 分钟前
MergeCell 合并机制:双平台事件流去重
后端
SemiTris14 分钟前
为什么 C/C++ 不走 Java 式的虚拟机跨平台路线?
java·程序员
予怀96016 分钟前
ClickHouse踩坑:一个sum()引发的"数字不一致"悬案
后端
橘色的喵23 分钟前
ReclaimBatcher 批量回收:RT-Thread 单核与 Linux SMP 通用
后端
weixin_4407841131 分钟前
【IntentSeivice实现原理】
android·java·开发语言·intentservice