spring boot 全局异常处理通过 @restcontrolleradvice 结合 @exceptionhandler 来捕获扩展点异常。具体做法是定义一个实现了特定扩展接口(如 handlerexceptionresolver)的 bean,或者在 @restcontrolleradvice 中显式声明需要处理的异常类型。这样当请求触发这些异常时,框架会自动将控制权交给你的处理器,返回统一的错误响应。

如何配置全局异常处理器类
要捕获扩展点异常,首先需要创建一个被 @RestControllerAdvice 注解标记的类。这个类会作为全局异常拦截器,自动扫描所有 Controller 抛出的异常。你需要在这个类中定义方法,并使用 @ExceptionHandler 指定要捕获的具体异常类型。例如,如果有一个自定义的 BusinessException,你可以直接在其参数列表中声明该类型,Spring 就会在发生该异常时调用此方法。

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResponseEntity<String> handleBusinessException(BusinessException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGenericException(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error");
}
}上述代码定义了两个异常处理方法。第一个专门处理 BusinessException,返回 400 状态码和错误信息;第二个处理所有其他未捕获的 Exception,返回 500 状态码。这种分层处理确保了不同级别的异常能得到适当的响应。
如何处理特定业务逻辑中的异常
在实际业务中,我们通常会在 Service 层抛出特定的业务异常。为了验证全局异常处理是否生效,我们需要在 Controller 或 Service 中模拟抛出这些异常。通过编写一个简单的测试用例或直接在 Controller 中触发异常,可以观察全局异常处理器的行为。关键在于确保异常确实是从受管组件中抛出的,并且没有被局部 try-catch 块吞掉。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class TestController {
@GetMapping("/test")
public String test() {
// 模拟业务异常
throw new BusinessException("Something went wrong in business logic");
}
}当访问 /api/test 端点时,TestController 会抛出 BusinessException。由于没有局部的 try-catch,该异常会向上冒泡,最终被 GlobalExceptionHandler 中的 handleBusinessException 方法捕获。客户端将收到一个包含 "Something went wrong in business logic" 消息的 400 响应。这证明了全局异常处理器能够正确拦截并处理来自业务层的异常。
基于程序中某个输入、条件或结果的具体问题
当程序接收到空值或无效输入时,全局异常处理器如何表现?在上述示例中,如果 BusinessException 的消息为空字符串,处理器仍然会返回 400 状态码,但响应体为空。这是因为 handleBusinessException 方法直接返回了 ex.getMessage(),而没有对消息内容进行非空校验。开发者需要注意,在全局异常处理中,应始终对异常信息进行必要的清理或默认化处理,以避免向客户端暴露敏感信息或返回无意义的空响应。


















