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

相关推荐
尚早立志4 分钟前
Spring Boot 源码研读之ConfigurableEnvironment 环境准备
java·spring boot·后端
YuK.W5 分钟前
Leetcode100: 94.二叉树中序遍历、104.二叉树最大深度、226.翻转二叉树
java·算法·leetcode·二叉树
乂爻yiyao12 分钟前
0. openems 部署与体验
java·openems
TanYYF19 分钟前
spring ai入门教程一
java·人工智能·spring
掉鱼的猫24 分钟前
用 ChatModel 构建 LLM 驱动的 Java 应用
java·llm
41541127 分钟前
JTS 空间运算实战:线 × 线、线 × 面、面 × 面叠加分析
java·jts·叠加分析
布朗克16840 分钟前
Go 入门到精通-08-复合类型之数组与切片
开发语言·后端·golang·数组与切片
fliter43 分钟前
从手写 HTTP/1.1 到拆开 HTTP/2
后端
.Hypocritical.44 分钟前
数据结构笔记——链表成环/反转 + 有序二叉树(BST)构建、遍历、删除
java·数据结构
CaffeinePro1 小时前
FastAPI自动接口文档定制与美化、权限管控
后端·fastapi