java 使用Spring Webflux Webclient记录错误状态代码和错误状态消息

dldeef67  于 2023-05-15  发布在  Java
关注(0)|答案(1)|浏览(172)
  • 我想达到的目标:*

向外部API发送带有MyPojo体的http请求,并返回原始MyPojo。但是当出现错误(外部API没有返回200)时,记录错误代码和错误消息体(不抛出任何东西!)并仍然返回原始的MyPojo。

  • 我尝试了什么 *
public Flux<MyPojo> question (Flux<MyPojo> myPojoFlux) {
        return myPojoFlux.flatMap(myPojo -> webClient.post().bodyValue(myPojo).exchangeToMono(clientResponse -> logStatusCodeAndErrorBodyWhenNotStatusOk(clientResponse, myPojo)));
    }

    private Mono<MyPojo> logStatusCodeAndErrorBodyWhenNotStatusOk(final ClientResponse clientResponse, final MyPojomyPojo) {
        if (200 != clientResponse.statusCode().value()) {
            //Not able to get the error message body :'(
            LOGGER.warn("The third party API responded status code {} with error message body {} for this request payload {}", clientResponse.statusCode().value(), myPojo, null);
            //Note: I do not want to throw any exception here
        }
//return the original payload mypojo object
        return Mono.just(myPojo);
    }

我也试过onError,onStatus,没有运气

  • 问题:*

有了这个结构,我就可以得到状态码,但不能得到错误消息体,同时用Mono.just(myPojo)返回一个奇怪的Mono;
如何记录状态代码和错误消息正文,而不(抛出任何东西)并且能够返回原始请求有效负载?

blpfk2vs

blpfk2vs1#

这可能就是你正在寻找的:

public Flux<MyPojo> question(Flux<MyPojo> myPojoFlux) {
    return myPojoFlux.flatMap(myPojo -> webClient.post()
        .bodyValue(myPojo)
        .exchangeToMono(clientResponse -> {
            if (clientResponse.statusCode().is2xxSuccessful()) {
                return clientResponse
                    .releaseBody() // be a good citizen and consume the body
                    .thenReturn(myPojo);
            } else {
                return clientResponse
                    .bodyToMono(String.class) // consume the body to construct response
                    .doOnNext(response -> LOG.warn("Error {} occurred. HTTP status code was {}", response, clientResponse.statusCode()))
                    .thenReturn(myPojo);
            }
        })
    );
}

相关问题