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

相关推荐
艾菜籽19 小时前
Spring Web MVC入门补充1
java·后端·spring·mvc
用户34216749055219 小时前
SVN高级视频教程
后端
洛卡卡了19 小时前
从被动救火到主动预警,接入 Prometheus + Grafana 全流程
后端·面试·架构
失散1319 小时前
分布式专题——44 ElasticSearch安装
java·分布式·elasticsearch·架构
无限进步_19 小时前
扫雷游戏的设计与实现:扫雷游戏3.0
c语言·开发语言·c++·后端·算法·游戏·游戏程序
追逐时光者19 小时前
使用 Visual Studio 快速创建 NuGet 程序包并发布到 NuGet 官网
后端·.net·visual studio
MicrosoftReactor19 小时前
技术速递|使用 GitHub Copilot Agent 模式现代化 Java 项目的分步指南
java·github·copilot
ahauedu20 小时前
Spring Boot 2.7+ 中 RedisConnectionFactory Autowire 警告的深度解析
java·spring boot·后端
im_AMBER20 小时前
杂记 15
java·开发语言·算法