导读:本期聚焦于小伙伴创作的《Spring Boot REST API 如何实现统一异常处理》,敬请观看详情,探索知识的价值。以下视频、文章将为您系统阐述其核心内容与价值。如果您觉得《Spring Boot REST API 如何实现统一异常处理》有用,将其分享出去将是对创作者最好的鼓励。

在Spring Boot REST API开发中,零散的异常处理会让接口返回格式不统一,还会泄露服务端内部信息,统一异常处理是解决这类问题的有效方案。下面我们来看具体的实现方法。

Spring Boot REST API 如何实现统一异常处理

为什么需要统一异常处理

没有统一异常处理时,接口抛出异常会返回Spring默认的错误页面或者杂乱的JSON信息,存在几个明显问题:

  • 错误响应格式不统一,前端需要适配多种不同的错误结构,增加开发成本
  • 可能暴露数据库报错、堆栈信息等敏感内容,带来安全风险
  • 业务异常和系统异常没有区分,无法给前端返回明确的错误提示

核心实现方案

Spring Boot提供了@ControllerAdvice注解,配合@ExceptionHandler可以实现全局异常捕获,结合ResponseEntity可以自定义返回的状态码和响应体。

1. 定义统一错误响应结构

首先我们需要定义一个标准的错误响应实体,让所有异常返回的格式保持一致:

public class ErrorResponse {
    private Integer code;
    private String message;
    private Long timestamp;

    public ErrorResponse(Integer code, String message) {
        this.code = code;
        this.message = message;
        this.timestamp = System.currentTimeMillis();
    }

    // getter和setter方法
    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Long timestamp) {
        this.timestamp = timestamp;
    }
}

2. 定义自定义业务异常

我们可以自定义业务异常类,用来区分不同的业务错误场景:

public class BusinessException extends RuntimeException {
    private Integer code;

    public BusinessException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}

3. 编写全局异常处理器

使用@ControllerAdvice注解标记全局异常处理类,在里面编写不同异常的处理方法:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    // 处理自定义业务异常
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ErrorResponse> handleBusinessException(BusinessException e) {
        ErrorResponse errorResponse = new ErrorResponse(e.getCode(), e.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.valueOf(e.getCode()));
    }

    // 处理参数校验异常
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ErrorResponse> handleIllegalArgumentException(IllegalArgumentException e) {
        ErrorResponse errorResponse = new ErrorResponse(400, e.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
    }

    // 处理其他未捕获的异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleException(Exception e) {
        ErrorResponse errorResponse = new ErrorResponse(500, "系统内部错误,请联系管理员");
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

使用示例

在Controller中抛出异常时,会被全局异常处理器自动捕获并返回统一格式:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/user")
    public String getUser(@RequestParam Integer id) {
        if (id == null || id <= 0) {
            throw new BusinessException(400, "用户ID必须为正整数");
        }
        if (id == 999) {
            throw new BusinessException(404, "用户不存在");
        }
        return "用户ID:" + id;
    }
}

注意事项

  • 自定义异常的错误码建议和HTTP状态码对应,方便前端处理
  • 全局异常处理器中不要捕获并返回过于详细的堆栈信息,避免敏感信息泄露
  • 如果有特殊的异常需要处理,可以在全局异常处理器中新增对应的@ExceptionHandler方法
  • 可以结合参数校验框架的异常,统一处理校验失败的错误信息,减少重复代码

通过上面的方案,我们可以快速实现Spring Boot REST API的统一异常处理,让接口返回的错误信息更规范,也提升了系统的安全性和可维护性。

Spring_BootREST_API统一异常处理@ControllerAdviceResponseEntity修改时间:2026-05-30 23:49:56

免责声明:​ 已尽一切努力确保本网站所含信息的准确性。网站内容多为原创整理与精心编撰,观点力求客观中立。本站旨在免费分享,内容仅供个人学习、研究或参考使用。若引用了第三方作品,版权归原作者所有。如内容涉及您的权益,请联系我们处理。
内容垂直聚焦
专注技术核心技术栏目,确保每篇文章深度聚焦于实用技能。从代码技巧到架构设计,为用户提供无干扰的纯技术知识沉淀,精准满足专业提升需求。
知识结构清晰
覆盖从开发到部署的全链路。AI、前端、编程、数据库、服务器、建站、系统层层递进,构建清晰学习路径,帮助用户系统化掌握开发与运维所需的核心技术。
深度技术解析
拒绝泛泛而谈,深入技术细节与实践难点。无论是数据库优化还是服务器配置,均结合真实场景与代码示例进行剖析,致力于提供可直接应用于工作的解决方案。
专业领域覆盖
精准对应开发生命周期。从前端界面到后端编程,从数据库操作到服务器运维,形成完整闭环,一站式满足全栈工程师和运维人员的技术需求。
即学即用高效
内容强调实操性,步骤清晰、代码完整。用户可根据教程直接复现和应用于自身项目,显著缩短从学习到实践的距离,快速解决开发中的具体问题。
持续更新保障
专注既定技术方向进行长期、稳定的内容输出。确保各栏目技术文章持续更新迭代,紧跟主流技术发展趋势,为用户提供经久不衰的学习价值。