spring boot 全局异常处理可以通过实现 handlerexceptionresolver 接口或配置 @controlleradvice 来捕获观察者通知中的异常。具体做法是在全局异常处理器中定义针对特定异常类型的处理方法,并在其中记录日志或返回统一响应。

如何配置全局异常处理器以捕获自定义异常?
通过创建继承自 ResponseEntityExceptionHandler 的类并添加 @RestControllerAdvice 注解,可以拦截所有控制器抛出的异常。对于观察者模式中的自定义异常,只需在方法参数中使用 @ExceptionHandler 指定异常类型即可。

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(CustomObserverException.class)
public ResponseEntity<string> handleCustomException(CustomObserverException ex) {
return new ResponseEntity(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}</string>
如何处理未预期的运行时异常?
除了处理已知的自定义异常外,还需要设置一个兜底方法来捕获所有未被处理的 RuntimeException。这确保了即使观察者逻辑中出现意外错误,系统也不会崩溃而是返回友好的错误信息。

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<string> handleRuntimeException(RuntimeException ex) {
return new ResponseEntity("An unexpected error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}</string>
当观察者抛出空指针异常时全局处理器会如何响应?
如果观察者在执行过程中抛出 NullPointerException,由于它属于 RuntimeException 的子类,因此会被上述第二个示例中的兜底方法捕获。此时系统将返回包含详细错误信息的 HTTP 500 状态码响应。











