使用 @restcontrolleradvice 配合 @exceptionhandler 可以捕获系统异常。只需定义一个全局异常处理类,并在其中编写处理 exception 或具体业务异常的逻辑,spring boot 会自动将未处理的异常路由到这些方法中。

@RestControllerAdvice 如何拦截异常
通过继承 ResponseEntityExceptionHandler 或直接声明注解,该类会扫描所有 Controller 抛出的异常。当 Controller 中发生异常且未被局部 try-catch 处理时,框架会查找匹配的 @ExceptionHandler 方法并执行。

import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<string> handleAllExceptions(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("System Error: " + ex.getMessage());
}
}</string>
如何区分处理特定业务异常
在同一个 @RestControllerAdvice 类中,可以添加多个 @ExceptionHandler 方法来处理不同的异常类型。例如,针对自定义的 BusinessException 返回特定的错误码和消息,而通用异常则记录日志并返回默认错误信息。

import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
// 假设有一个自定义异常类
// public class BusinessException extends RuntimeException { ... }
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResponseEntity<string> handleBusinessException(BusinessException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Business Error: " + ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<string> handleAllExceptions(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("System Error: " + ex.getMessage());
}
}</string></string>
如何处理空指针异常的具体场景
当代码中出现 NullPointerException 时,它会被 Exception.class 的处理器捕获。可以通过在 @ExceptionHandler 中检查异常类型来提供更具针对性的反馈,或者统一由通用处理器处理并记录详细堆栈信息以便排查。











