小编Nic*_*rbé的帖子

使用webflux处理异常并返回正确的HTTP代码

我正在使用WebFlux的功能端点.我使用onErrorResume以下方法将服务层发送的异常转换为HTTP错误代码:

public Mono<String> serviceReturningMonoError() {
    return Mono.error(new RuntimeException("error"));  
}

public Mono<ServerResponse> handler(ServerRequest request) {
    return serviceReturningMonoError().flatMap(e -> ok().syncBody(e))
                            .onErrorResume( e -> badRequest(e.getMessage()));
}
Run Code Online (Sandbox Code Playgroud)

一旦服务返回Mono,它就能很好地工作.如果服务返回Flux,我该怎么办?

public Flux<String> serviceReturningFluxError() {
    return Flux.error(new RuntimeException("error"));  
}

public Mono<ServerResponse> handler(ServerRequest request) {
    ???
}
Run Code Online (Sandbox Code Playgroud)

编辑

我尝试了下面的方法,但不幸的是它不起作用.Flux.error不会被onErrorResume传播并传播到框架.当在http响应的序列化期间取消装箱异常时,Spring Boot异常管理会捕获它并将其转换为500.

public Mono<ServerResponse> myHandler(ServerRequest request) {
      return ok().contentType(APPLICATION_JSON).body( serviceReturningFluxError(), String.class)
             .onErrorResume( exception -> badRequest().build());
}
Run Code Online (Sandbox Code Playgroud)

我实际上对这个行为感到惊讶,那是一个bug吗?

spring spring-boot project-reactor spring-webflux

5
推荐指数
1
解决办法
4403
查看次数