相关类
WebExceptionHandler
public interface WebExceptionHandler {Mono handle(ServerWebExchange exchange, Throwable ex);}
ErrorWebExceptionHandler
@FunctionalInterfacepublic interface ErrorWebExceptionHandler extends WebExceptionHandler {}
自定义全局异常处理
GlobalExceptionHandler
@Component@Slf4jpublic class GlobalExceptionHandler implements ErrorWebExceptionHandler {// 打印日志时使用 private static final String ERROR_STACKTRACE = "Stacktrace:"; // 异常返回的状态码 private static final String KEY_STATUS = "httpStatus"; // 异常返回信息主体 private static final String KEY_BODY = "body"; private Tracer tracer; public void setTracer(Tracer tracer) { this.tracer = tracer; } private final ObjectMapper objectMapper = new ObjectMapper(); private List> messageReaders = Collections.emptyList(); private List> messageWriters = Collections.emptyList(); private List viewResolvers = Collections.emptyList(); private final ThreadLocal
CustomExceptionResponse :
@Getter@Setter@AllArgsConstructor@NoArgsConstructorpublic class CustomExceptionResponse { private String errorCode; private String message; private String path;}
ExceptionConfig:
@Configurationpublic class ExceptionConfig { @Primary @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public ErrorWebExceptionHandler errorWebExceptionHandler(ObjectProvider> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer, Tracer tracer) { GlobalExceptionHandler globalExceptionHandler = new GlobalExceptionHandler(); globalExceptionHandler.setTracer(tracer); globalExceptionHandler.setViewResolvers(viewResolversProvider.getIfAvailable(Collections::emptyList)); globalExceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters()); globalExceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders()); return globalExceptionHandler; }}