news 2026/8/24 16:16:36

Spring Boot统一异常处理

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Spring Boot统一异常处理

在Spring Boot中实现统一异常处理主要通过@ControllerAdvice@ExceptionHandler注解组合完成。这种方式能集中处理控制器层抛出的异常,避免在每个方法中重复编写异常处理代码。

基础实现步骤

创建全局异常处理类并添加@ControllerAdvice注解。这个类可以包含多个异常处理方法:

@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleException(Exception ex) { ErrorResponse error = new ErrorResponse( HttpStatus.INTERNAL_SERVER_ERROR.value(), "Internal Server Error", ex.getMessage() ); return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR); } }

定义统一的错误响应体结构:

@Data @AllArgsConstructor public class ErrorResponse { private int status; private String error; private String message; private String timestamp = LocalDateTime.now().toString(); }

处理特定异常类型

针对不同的异常类型定义具体的处理方法:

@ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ErrorResponse> handleResourceNotFound( ResourceNotFoundException ex) { ErrorResponse error = new ErrorResponse( HttpStatus.NOT_FOUND.value(), "Resource Not Found", ex.getMessage() ); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ErrorResponse> handleValidationExceptions( MethodArgumentNotValidException ex) { List<String> errors = ex.getBindingResult() .getFieldErrors() .stream() .map(FieldError::getDefaultMessage) .collect(Collectors.toList()); ErrorResponse error = new ErrorResponse( HttpStatus.BAD_REQUEST.value(), "Validation Error", errors.toString() ); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); }

自定义异常类

创建业务特定的异常类型:

public class BusinessException extends RuntimeException { private final ErrorCode errorCode; public BusinessException(ErrorCode errorCode, String message) { super(message); this.errorCode = errorCode; } public ErrorCode getErrorCode() { return errorCode; } }

对应的异常处理:

@ExceptionHandler(BusinessException.class) public ResponseEntity<ErrorResponse> handleBusinessException( BusinessException ex) { ErrorResponse error = new ErrorResponse( ex.getErrorCode().getCode(), ex.getErrorCode().name(), ex.getMessage() ); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); }

响应内容协商支持

确保异常处理支持多种响应格式(JSON/XML等):

@ControllerAdvice @RequestMapping(produces = {"application/json", "application/xml"}) public class GlobalExceptionHandler { // 处理方法保持不变 }

日志记录集成

在异常处理中加入日志记录:

@ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleException(Exception ex) { logger.error("Unexpected error occurred", ex); // 其余处理逻辑 }

测试验证方法

编写测试用例验证异常处理:

@SpringBootTest @AutoConfigureMockMvc class ExceptionHandlerTest { @Autowired private MockMvc mockMvc; @Test void testResourceNotFound() throws Exception { mockMvc.perform(get("/api/resource/999")) .andExpect(status().isNotFound()) .andExpect(jsonPath("$.error").value("Resource Not Found")); } }

这种实现方式提供了清晰的异常处理结构,使业务代码保持整洁,同时为客户端返回标准化的错误响应。根据项目需求可以进一步扩展,如添加多语言支持、更详细的错误分类等。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/8/24 8:39:19

Dify可视化AI应用开发平台的核心优势全面揭秘

Dify可视化AI应用开发平台的核心优势全面揭秘 在大模型技术席卷全球的今天&#xff0c;企业对AI落地的期待从未如此迫切。然而现实却常常令人沮丧&#xff1a;一个看似简单的智能客服系统&#xff0c;动辄需要数周甚至数月的开发周期&#xff1b;提示词稍作调整&#xff0c;整个…

作者头像 李华
网站建设 2026/8/23 18:07:16

3个结构化数据技巧,让你的GEO收录率飙升200%

在AI主导的信息获取时代&#xff0c;GEO&#xff08;生成引擎优化&#xff09;已成为企业内容战略的核心战场。据水滴互动2025年行业白皮书数据显示&#xff0c;采用结构化数据优化的企业&#xff0c;其内容被AI引擎引用的概率提升2.3倍&#xff0c;决策链路转化率提高47%。本文…

作者头像 李华
网站建设 2026/8/24 8:07:36

Linux实时调度:3大策略对比与实战配置指南 [特殊字符]

Linux实时调度&#xff1a;3大策略对比与实战配置指南 &#x1f680; 【免费下载链接】linux-insides-zh Linux 内核揭秘 项目地址: https://gitcode.com/gh_mirrors/li/linux-insides-zh 还在为系统响应延迟而烦恼&#xff1f;Linux内核的实时调度机制正是你需要的解决…

作者头像 李华
网站建设 2026/8/23 14:51:14

CasperJS API测试实战指南:前后端数据一致性验证的高效方案

CasperJS API测试实战指南&#xff1a;前后端数据一致性验证的高效方案 【免费下载链接】casperjs CasperJS is no longer actively maintained. Navigation scripting and testing utility for PhantomJS and SlimerJS 项目地址: https://gitcode.com/gh_mirrors/ca/casperj…

作者头像 李华