spring boot 全局异常处理通过 @restcontrolleradvice 配合 @exceptionhandler 捕获告警触发时抛出的自定义异常。具体做法是定义一个继承自 runtimeexception 的告警异常类,在业务逻辑中抛出该异常,并在控制器增强器中拦截它返回统一的 json 响应。这样能确保告警触发时的错误被统一格式化处理,避免暴露堆栈信息。

如何定义告警触发异常类
告警触发异常需要继承 RuntimeException 以便在不强制声明的情况下传播。该类应包含错误码和消息字段,用于后续的全局处理。

public class AlertTriggeredException extends RuntimeException {
private final String errorCode;
public AlertTriggeredException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
}
如何在业务层触发并捕获异常
业务服务在检测到告警条件时抛出异常,全局异常处理器拦截并返回标准响应。以下代码展示了完整的控制器、服务和异常处理器实现。

// AlertService.java
@Service
public class AlertService {
public void checkAlert(int threshold) {
if (threshold > 100) {
throw new AlertTriggeredException("ALERT_001", "Threshold exceeded");
}
}
}
// AlertController.java
@RestController
public class AlertController {
@Autowired
private AlertService alertService;
@GetMapping("/check")
public ResponseEntity<string> check(@RequestParam int threshold) {
alertService.checkAlert(threshold);
return ResponseEntity.ok("OK");
}
}
// GlobalExceptionHandler.java
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(AlertTriggeredException.class)
public ResponseEntity<map object>> handleAlertException(AlertTriggeredException ex) {
Map<string object> body = new HashMap();
body.put("error", ex.getErrorCode());
body.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
}
}</string></map></string>
当阈值等于100时全局异常处理会捕获吗
当阈值等于100时,全局异常处理不会捕获异常,因为业务逻辑中的条件是大于100才抛出异常。此时请求正常返回“OK”。











