使用 @restcontrolleradvice 配合 @exceptionhandler 注解可以全局捕获接口调用异常。在配置类中定义一个带有这两个注解的组件,并在方法参数中指定需要捕获的异常类型,spring boot 会自动拦截控制器抛出的对应异常并执行该方法返回统一响应。

如何捕获自定义业务异常
通过继承 RuntimeException 创建自定义异常类,并在 @RestControllerAdvice 中针对该自定义类编写处理逻辑即可。当业务代码抛出该异常时,全局处理器会优先匹配并返回预设的业务错误信息。

package com.example.demo;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomBusinessException.class)
public ResponseEntity<string> handleCustomException(CustomBusinessException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
}
}</string>
如何处理未捕获的通用异常
在全局异常处理器中添加一个不指定具体类型的 @ExceptionHandler 方法,或者专门捕获 Exception 类,可以兜底处理所有未被其他处理器捕获的运行时异常。这能防止因未知错误导致服务器返回默认的 500 页面或堆栈跟踪信息暴露给前端。

package com.example.demo;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<string> handleGenericException(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("System Error");
}
}</string>
全局异常处理对接口返回值的具体影响
全局异常处理会将原本会导致 HTTP 500 错误的异常转换为 HTTP 200 或指定的状态码,并返回 JSON 格式的错误描述。这种机制确保了无论发生何种异常,客户端都能接收到结构一致的数据,便于前端进行统一的错误提示和流程控制。











