Spring Boot 自定义异常处理失效的完整解决方案

夜静大大_3686

夜静大大_3686

2026-08-21

735人浏览

原创

Spring Boot 自定义异常处理失效的完整解决方案

本文详解 spring boot 中自定义异常(如 resourcenotfoundexception)无法正确返回 json 响应的常见原因,重点修复全局异常处理器未生效、异常响应体为空、逻辑判断错误等问题,并提供可直接运行的规范实现。

本文详解 spring boot 中自定义异常(如 resourcenotfoundexception)无法正确返回 json 响应的常见原因,重点修复全局异常处理器未生效、异常响应体为空、逻辑判断错误等问题,并提供可直接运行的规范实现。

在 Spring Boot 项目中,当通过 @ControllerAdvice 实现全局异常处理时,若自定义异常(如 ResourceNotFoundException)在 Postman 中无响应或返回空内容,通常并非配置遗漏,而是存在逻辑缺陷 + 响应结构不匹配 + 异常未被正确捕获三重问题。下面将逐层剖析并给出生产级解决方案。

? 根本问题定位

  1. getSingleToDo() 方法逻辑错误
    原代码中:

    ToDo todo = new ToDo(); // 初始化为新对象,非 null!
    for (ToDo todo1 : todos) {
        if (todo1.getId() == id) return todo1;
        todo = todo1; // 每次都赋值,循环结束 todo 必不为 null
    }
    if (todo == null) { ... } // 此条件永远不成立 → 异常永不抛出!

    ✅ 修正方案:移除冗余变量,直接在循环后抛出异常:

    public ToDo getSingleToDo(int id) {
        for (ToDo todo : todos) {
            if (todo.getId() == id) {
                return todo;
            }
        }
        // 循环结束仍未找到 → 明确抛出异常
        throw new ResourceNotFoundException("Todo with id " + id + " not found", HttpStatus.NOT_FOUND);
    }
  2. ExceptionResponse 缺少必要字段序列化支持
    当前类仅有 getter/setter,但未标注 @Getter/@Setter(Lombok)或未确保字段可被 Jackson 序列化。更关键的是:HttpStatus 类型无法直接 JSON 序列化(默认输出为枚举全限定名或空对象),导致响应体为空或格式异常。

    ✅ 修正方案:改用 int 或 String 表示状态码,并添加 @JsonInclude(Include.NON_NULL) 避免空字段:

    package com.lcwd.todo.exceptions;
    
    import com.fasterxml.jackson.annotation.JsonInclude;
    import com.fasterxml.jackson.annotation.JsonInclude.Include;
    
    @JsonInclude(Include.NON_NULL)
    public class ExceptionResponse {
        private String message;
        private boolean success;
        private int statusCode; // ✅ 使用 int 替代 HttpStatus
        private String status;  // ✅ 可选:如 "NOT_FOUND"
    
        public ExceptionResponse(String message, boolean success, int statusCode, String status) {
            this.message = message;
            this.success = success;
            this.statusCode = statusCode;
            this.status = status;
        }
    
        // 省略 getter/setter(务必生成!)
    }
  3. GlobalExceptionHandler 中的响应构造不严谨
    原代码重复调用 response.setMessage(...),且未设置 statusCode 和 status 字段:

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<exceptionresponse> resourceNotFoundExceptionHandler(ResourceNotFoundException ex) {
        ExceptionResponse response = new ExceptionResponse();
        response.setMessage(ex.getMessage()); // ❌ 重复设置
        response.setMessage(ex.getMessage());
        response.setSuccess(false);
        // ❌ statusCode 和 status 未赋值 → JSON 中为 0/null
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
    }</exceptionresponse>

    ✅ 修正方案:使用构造函数初始化,并显式传递状态码与状态文本:

    Spring Boot 3.3.13
    Spring Boot 3.3.13

    Spring Boot下载页提供 3.3.13 官方源码 ZIP,并整理快速入门、项目创建、配置和自动配置说明。

    下载
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<exceptionresponse> resourceNotFoundExceptionHandler(ResourceNotFoundException ex) {
        ExceptionResponse response = new ExceptionResponse(
                ex.getMessage(),
                false,
                ex.getStatus().value(), // ✅ 获取 HTTP 状态码数值
                ex.getStatus().getReasonPhrase() // ✅ 如 "Not Found"
        );
        return ResponseEntity.status(ex.getStatus()).body(response);
    }</exceptionresponse>
  4. ResourceNotFoundException 构造函数未透传 HttpStatus
    当前构造函数接收 HttpStatus 但未在异常类中持久化(仅在父类 RuntimeException 中存储 message),导致处理器中 ex.getStatus() 无法获取。

    ✅ 修正方案:在异常类中保留 HttpStatus 字段,并提供安全的 getStatus() 方法:

    public class ResourceNotFoundException extends RuntimeException {
        private final HttpStatus status;
    
        public ResourceNotFoundException(String message, HttpStatus status) {
            super(message);
            this.status = status != null ? status : HttpStatus.NOT_FOUND;
        }
    
        public HttpStatus getStatus() {
            return status;
        }
    }

✅ 完整可运行示例(整合后)

// ExceptionResponse.java
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ExceptionResponse {
    private String message;
    private boolean success;
    private int statusCode;
    private String status;

    public ExceptionResponse(String message, boolean success, int statusCode, String status) {
        this.message = message;
        this.success = success;
        this.statusCode = statusCode;
        this.status = status;
    }
    // ... getter/setter(IDE 自动生成)
}
// GlobalExceptionHandler.java
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<exceptionresponse> handleResourceNotFound(ResourceNotFoundException ex) {
        ExceptionResponse response = new ExceptionResponse(
                ex.getMessage(),
                false,
                ex.getStatus().value(),
                ex.getStatus().getReasonPhrase()
        );
        logger.warn("Resource not found: {}", ex.getMessage());
        return ResponseEntity.status(ex.getStatus()).body(response);
    }

    // 兜底异常处理器(推荐)
    @ExceptionHandler(Exception.class)
    public ResponseEntity<exceptionresponse> handleGeneric(Exception ex) {
        ExceptionResponse response = new ExceptionResponse(
                "Internal server error",
                false,
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()
        );
        logger.error("Unhandled exception", ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
    }
}</exceptionresponse></exceptionresponse>

⚠️ 注意事项与最佳实践

  • 确保 @ControllerAdvice 被组件扫描到:检查包路径是否在 @SpringBootApplication 扫描范围内,或显式指定 @ComponentScan(basePackages = "com.lcwd.todo")。
  • 避免在 DTO 中使用 HttpStatus:JSON 序列化器无法自动转换 HttpStatus,始终转为 int 或 String。
  • 启用日志验证:在 GlobalExceptionHandler 中添加 logger.warn() / logger.error(),确认异常是否真正进入处理器。
  • Postman 测试技巧:发送不存在 ID 的 GET 请求(如 /api/todos/999),观察响应状态码是否为 404,响应体是否为标准 JSON(如 {"message":"Todo with id 999 not found","success":false,"statusCode":404,"status":"Not Found"})。
  • 进阶建议:使用 @ResponseStatus 注解简化单异常处理,或集成 Problem Details RFC 7807 标准提升 API 规范性。

遵循以上修正,你的自定义异常将精准捕获、结构化响应,并在 Postman 中清晰可见——这才是 Spring Boot 全局异常处理的正确打开方式。

相关专题

更多
spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

2023.09.05

571

5

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

2023.10.12

1435

7

Java Spring Boot开发
Java Spring Boot开发

本专题围绕 Java 主流开发框架 Spring Boot 展开,系统讲解依赖注入、配置管理、数据访问、RESTful API、微服务架构与安全认证等核心知识,并通过电商平台、博客系统与企业管理系统等项目实战,帮助学员掌握使用 Spring Boot 快速开发高效、稳定的企业级应用。

2025.08.19

4326

10

Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性
Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性

Spring Boot 是一个基于 Spring 框架的 Java 开发框架,它通过 约定优于配置的原则,大幅简化了 Spring 应用的初始搭建、配置和开发过程,让开发者可以快速构建独立的、生产级别的 Spring 应用,无需繁琐的样板配置,通常集成嵌入式服务器(如 Tomcat),提供“开箱即用”的体验,是构建微服务和 Web 应用的流行工具。

2025.12.22

436

5

Java Spring Boot 微服务实战
Java Spring Boot 微服务实战

本专题深入讲解 Java Spring Boot 在微服务架构中的应用,内容涵盖服务注册与发现、REST API开发、配置中心、负载均衡、熔断与限流、日志与监控。通过实际项目案例(如电商订单系统),帮助开发者掌握 从单体应用迁移到高可用微服务系统的完整流程与实战能力。

2025.12.24

620

18

Spring Boot企业级开发与MyBatis Plus实战
Spring Boot企业级开发与MyBatis Plus实战

本专题面向 Java 后端开发者,系统讲解如何基于 Spring Boot 与 MyBatis Plus 构建高效、规范的企业级应用。内容涵盖项目架构设计、数据访问层封装、通用 CRUD 实现、分页与条件查询、代码生成器以及常见性能优化方案。通过完整实战案例,帮助开发者提升后端开发效率,减少重复代码,快速交付稳定可维护的业务系统。

2026.02.11

365

24

Kotlin协程编程与Spring Boot集成实践
Kotlin协程编程与Spring Boot集成实践

本专题围绕 Kotlin 协程机制展开,深入讲解挂起函数、协程作用域、结构化并发与异常处理机制,并结合 Spring Boot 展示协程在后端开发中的实际应用。内容涵盖异步接口设计、数据库调用优化、线程资源管理以及性能调优策略,帮助开发者构建更加简洁高效的 Kotlin 后端服务架构。

2026.02.12

331

18

Spring Boot 项目开发与实战
Spring Boot 项目开发与实战

以 Spring Boot 为核心,讲解项目的快速初始化(Spring Initializr)、自动配置与 Starter 依赖原理、配置文件(application.yml)多环境管理、RESTful API 接口开发与参数校验、MyBatis / MyBatis-Plus / Spring Data JPA 数据持久层整合、Redis 缓存集成、统一异常处理与全局响应封装、Swagger / Knife4j 接口文档生成,以及 Ma

2026.04.17

306

21

Java Spring Boot多租户架构设计与数据隔离实战
Java Spring Boot多租户架构设计与数据隔离实战

本专题聚焦 Java 企业级系统中的多租户架构设计,讲解数据隔离策略、租户路由机制、数据库分库分表方案以及权限控制模型。通过真实 SaaS 系统案例,帮助开发者构建可扩展的多租户应用架构。

2026.06.29

336

13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Spring Boot 官方快速入门指南
Spring Boot 官方快速入门指南

共0课时 | 0人学习

Spring Boot 官方参考文档
Spring Boot 官方参考文档

共0课时 | 0人学习

尚硅谷新版SpringBoot3教程
尚硅谷新版SpringBoot3教程

共0课时 | 0人学习