首页 > 解决方案 > Spring Webflux 单声道总是以成功的响应来响应

问题描述

我有一个端点,它接受 id 参数并发送删除产品 api 来删除。productService.delete 也返回 Mono。问题是当 productService.delete 方法返回单声道错误时,端点总是以 http 200 响应。我可以看到有关此单声道错误的错误日志,但我的处理程序方法响应 http 200。

我有一个 AbstractErrorWebExceptionHandler 来处理我的 api 中的异常。但是由于 Mono 的原因,错误处理程序无法处理此问题。当下游发生异常时,Spring webflux 应该知道这个错误并且不会响应 http 200。

    public Mono<ServerResponse> deleteProduct(ServerRequest request) {
     String id = request.pathVariable("id");
     Mono<Product> productMono = this.repository.findById(id);
     return productMono
            .flatMap(existingProduct ->
                    ServerResponse.noContent()
                            .build(productService.delete(existingProduct))
            );
}

顺便说一句,在源代码中,它表示将在给定发布者完成时提交响应。但是错误完成怎么样?我认为 Spring webflux 不会检查它是否是错误信号。只需检查单声道是否完成。

     * Build the response entity with no body.
     * The response will be committed when the given {@code voidPublisher} completes.
     * @param voidPublisher publisher publisher to indicate when the response should be committed
     * @return the built response
     */
    Mono<ServerResponse> build(Publisher<Void> voidPublisher);

先感谢您。

标签: functional-programmingmonospring-webfluxspring-reactivespring-mono

解决方案


该问题是由使用 voidPublisher 引起的。如果您使用 void 发布者创建 ServerResponse,它只会返回 http 200,即使您的下游完成并带有错误信号。它只是不关心你的流如何完成,它只关心下游的完成。

如果您想在构建响应时处理下游错误,只需简单使用

 ServerResponse.noContent()
    .body(productService.delete(existingProduct), Void.class)

现在,每当下游发生任何错误时,服务器都会以错误响应。


推荐阅读