Webclient 在错误时返回 ResponseEntity

问题描述 投票:0回答:0

我以前从未使用过 WebClient,但我必须使用它向外部 url 发送 Post 请求。之后我检查响应状态,如果是 204,我将继续该过程,但如果状态是某个错误代码,我应该发回从 ResponseEntity 接收到的错误消息。但是,如果请求收到错误代码,Web 客户端将发送异常,而不是返回 ResponseEntity。 代码如下所示:

Public ResponseEntity<Void> post(String uri, User value)
return webClient.post()
.uri(uri)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(value)
.retreive()
.toEntity(Void.class)
.timeout(properties.getTimeout)
.retryWhen(retry
    .filter(this::filterError)
    .doBefore(log.error("error message...")))
.block();

我希望 WebClient 发回完整的 responseEntity 而不是抛出异常。我试图寻找解决方案,但几乎每个帖子都只返回身体,并使用 bodyToMono。我不想要那个。

我试过像这样使用 onStatus,但是没用:

Public ResponseEntity<Void> post(String uri, User value)
return webClient.post()
.uri(uri)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(value)
.retreive()
.onStatus(HttpStatus::isError), clientResponse ->
    clientResponse.bodyToMono(String.class)
        .flatMap(error -> Mono.error(new RuntimeException(error)))
.toEntity(Void.class)
.timeout(properties.getTimeout)
.retryWhen(retry
    .filter(this::filterError)
    .doBefore(log.error("error message...")))
.block();

我也想使用 onErrorResume,但它返回 Mono,我不知道如何使用它。

还尝试使用 .exchange() 而不是 retreive() 但我发现它现在已被弃用,所以我回滚到 retreive。

Shell 我只是将使用 post 请求的代码包装到 try catch 块并捕获 WebClientResponseException.class ?这可能很难看,并且会在代码审查期间失败。 还有其他建议吗? 使用 Java17.

exception spring-webclient bad-request response-entity
© www.soinside.com 2019 - 2024. All rights reserved.