在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