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

相关推荐
码事漫谈21 分钟前
类型即世界:一个 C++ 程序员的本体论入门
后端
Rain的Java大神之路1 小时前
JavaWeb开发如何解决跨域问题
java·前端·后端·nginx·web安全·面试·运维开发
自动化监测Learner1 小时前
Navicat Premium 17 中文版安装教程(2026最新版)
java·linux·数据库
那个松鼠很眼熟w1 小时前
4.Spring-Ai入门案例
java·人工智能·spring
计算机毕设定制辅导-无忧学长1 小时前
《基于SpringBoot青年公寓出租管理系统的设计与实现》
java·vue.js·spring boot·青年公寓出租管理系统
泡海椒2 小时前
JQuick-Curl 二次开发:自定义解析器、扩展点开发指南,如何把框架能力真正变成团队资产
java·开发语言·okhttp·maven
MetaLite3 小时前
AI编程与工程底座-让AI遵守SpringBoot边界
人工智能·spring boot·ai编程
青山木3 小时前
Hot 100 --- 数组中的第K个最大元素
java·数据结构·算法·排序算法
玛卡巴卡ldf3 小时前
【AICoding】笔试提示词设计思路
java·算法·ai编程
IT_陈寒3 小时前
Python的多线程居然是个假把式?搞清GIL让我少熬三天夜
前端·人工智能·后端