使用 @controlleradvice 结合 @exceptionhandler 可以全局统一捕获并处理 controller 层的异常。具体做法是创建一个被 @restcontrolleradvice 或 @controlleradvice 注解的类,并在其中定义处理特定异常的方法,该方法需标注 @exceptionhandler 并指定要处理的异常类型,返回封装好的错误响应对象。

如何定义全局异常处理器类
定义一个配置类,添加 @RestControllerAdvice 注解使其自动生效。该类不需要实现任何接口,Spring Boot 会自动扫描并注册其中的异常处理方法。通过这种方式,所有 Controller 抛出的指定异常都会被拦截。

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(RuntimeException.class)
public ResponseEntity<errorresponse> handleRuntimeException(RuntimeException ex) {
ErrorResponse error = new ErrorResponse("500", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}</errorresponse>
上述代码中,GlobalExceptionHandler 类被 @RestControllerAdvice 标记。方法 handleRuntimeException 使用 @ExceptionHandler(RuntimeException.class) 声明它负责处理运行时异常。当 Controller 抛出未捕获的 RuntimeException 时,Spring 会调用此方法,返回包含错误码和消息的 JSON 响应。
如何处理自定义业务异常
对于特定的业务逻辑错误,应定义自定义异常类,并在 @ControllerAdvice 中单独处理。这样可以区分系统错误和业务错误,返回不同的 HTTP 状态码和错误信息,便于前端或调用方区分处理。

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.HttpStatus;
@ExceptionHandler(BusinessException.class)
public ResponseEntity<errorresponse> handleBusinessException(BusinessException ex) {
ErrorResponse error = new ErrorResponse(ex.getCode(), ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
}
// 自定义异常类示例
class BusinessException extends RuntimeException {
private String code;
public BusinessException(String code, String message) {
super(message);
this.code = code;
}
public String getCode() { return code; }
}</errorresponse>
在 GlobalExceptionHandler 中添加处理 BusinessException 的方法。该方法优先于通用异常处理,因为更具体的异常类型会被优先匹配。如果 Controller 抛出 BusinessException,将返回 400 状态码及自定义的错误码和消息。若未找到匹配的异常处理器,则回退到默认的全局异常处理机制。
当发生空指针异常时返回什么结果
当程序中出现 NullPointerException 且未被显式捕获时,它会作为 RuntimeException 的子类被全局处理器拦截。根据前文定义的 handleRuntimeException 方法,系统将返回 HTTP 500 状态码,响应体中的错误码为 "500",错误消息为 null pointer exception 的具体堆栈信息或默认提示。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











