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

相关推荐
程序员良辰8 分钟前
【TongWeb7的M11】 首次登录密码修改 & 开启控制台远程访问
java·中间件·tomcat
杨运交8 分钟前
[064][缓存模块]两级缓存实战:基于 Caffeine 和 Redis 的多级缓存设计与实现
spring boot
lichenyang4539 分钟前
NestJS + Socket.IO 鉴权、用户房间与幂等邀请
前端·后端
吴声子夜歌9 分钟前
Java面试——设计模式(四)
java·设计模式·面试
paopaokaka_luck10 分钟前
基于springboot3+vue3+uniapp的剧本杀预约小程序(AI角色对话、协同过滤算法、地图Api、Echarts图形化分析)
java·前端·spring boot·学习·echarts
lichenyang45310 分钟前
React 实时通知与异步竞态处理
前端·后端
一嘴一个橘子11 分钟前
idea 的 双击Shift 全局搜索
java·ide·intellij-idea
nvvas12 分钟前
最新版 IntelliJ IDEA 全面介绍:面向现代 Java 开发者的智能 IDE
java·ide·intellij-idea
circuitsosk16 分钟前
Python 文件读写与上下文管理器:with 语句为什么是最佳选择
java·服务器·python·文件操作·上下文管理器·contextlib