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

相关推荐
什巳1 小时前
JAVA练习278- 和为 K 的子数组
java·学习·算法·leetcode
豆瓣鸡1 小时前
RocketMQ学习-Spring Boot消息实践
java·spring boot·rocketmq
罗超驿2 小时前
2.算法效率的核心密码:时间复杂度和空间复杂度详解
java·数据结构·算法
栈溢出了3 小时前
Redis 分片集群与哈希槽笔记
java·redis·笔记·spring
这里是杨杨吖3 小时前
SpringBoot+Vue心理健康咨询系统 附带详细运行指导视频
spring boot·vue·心理健康
遨游DATA3 小时前
Spring Boot 启动失败排查:如何区分多 Bean 冲突与清理阶段异常
java·spring boot·后端
IT_陈寒3 小时前
Java线程池这个坑我算是踩明白了
前端·人工智能·后端
掉头发的王富贵3 小时前
我来入职新公司两个月了,为什么只写了100行代码?
后端·ai编程
从零开始的代码生活_3 小时前
C++ 内存管理:从内存分区到 new/delete 底层原理
开发语言·c++·后端