使用 @restcontrolleradvice 配合全局异常处理器可以统一捕获推送通知过程中的各类异常。具体做法是定义一个实现了 handlerexceptionresolver 或标注了 @controlleradvice 的类,并在其中编写处理特定推送异常(如 pushnotificationexception)的方法,该方法返回标准化的错误响应对象,从而避免业务代码中充斥大量的 try-catch 块。

如何配置全局异常处理器以拦截推送服务异常
通过继承 ResponseEntityExceptionHandler 并重写 handleExceptionInternal 方法,可以确保所有未捕获的推送异常都被转换为 HTTP 4xx 或 5xx 状态码及 JSON 格式的错误信息。核心在于将具体的推送异常类型映射到统一的错误结构体中。

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(PushNotificationException.class)
public ResponseEntity<ErrorResponse> handlePushException(PushNotificationException ex) {
ErrorResponse error = new ErrorResponse("PUSH_FAILED", ex.getMessage());
return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
推送通知失败时如何区分网络超时与认证错误
在推送通知场景中,通常需要根据异常的具体子类或消息内容来区分是网络层面的超时还是平台认证的失败。可以通过检查异常的 cause 或者自定义异常中的错误码字段来实现精细化的日志记录和客户端提示。

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class PushSpecificExceptionHandler {
@ExceptionHandler(NetworkTimeoutException.class)
public ResponseEntity<String> handleTimeout(NetworkTimeoutException ex) {
return new ResponseEntity<>("Network timeout, retry later", HttpStatus.GATEWAY_TIMEOUT);
}
@ExceptionHandler(AuthenticationFailedException.class)
public ResponseEntity<String> handleAuthError(AuthenticationFailedException ex) {
return new ResponseEntity<>("Invalid credentials", HttpStatus.UNAUTHORIZED);
}
}
当推送目标设备离线时全局异常处理器的行为是什么
如果推送服务在检测到设备离线时抛出特定的 DeviceOfflineException,全局异常处理器会捕获该异常并返回一个特定的状态码(如 410 Gone 或 200 OK 配合业务错误码),告知调用方该设备当前不可达,但不一定视为系统级故障。


















