简体   繁体   English

如何访问 spring WebClient Retry 中的响应正文?

[英]How to access response body in spring WebClient Retry?

I have a WebClient that makes use of retries:我有一个使用重试的WebClient

webClient.retryWhen(
   Retry.backoff(3, Duration.ofSeconds(3)).filter(this::isRetryable)
)

private boolean isRetryable(Throwable throwable) {
    //TODO how access the json body?
}

Question: how can I evaluate the json response body during retry?问题:如何在重试期间评估 json 响应正文? Because I want to base the decision not only on status code, but on error content returned.因为我不仅要根据状态代码做出决定,还要根据返回的错误内容做出决定。

I assume you're using the retrieve() method of webclient, which will always throw an exception if the status code signals an error.我假设您正在使用 webclient 的retrieve()方法,如果状态代码发出错误信号,它将始终抛出异常。 You probably want to use exchangeToMono() instead, which won't throw an exception on a non-2xx status code, instead providing you the response to do as you please:您可能想使用exchangeToMono()代替,它不会在非 2xx 状态代码上引发异常,而是为您提供随心所欲的响应:

WebClient.create("http://my-endpoint.abc/endpoint")
        .get()
        .exchangeToMono(cr -> cr.bodyToMono(String.class).map(body -> {
            //return `Mono.error()` here if invalid - you have access to both body + statuscode (via cr.statusCode())
        })).retryWhen(
            Retry.backoff(3, Duration.ofSeconds(3)).filter(e -> e instanceof ExceptionThrownAbove)
        );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何重试 Spring WebClient 根据响应重试操作? - how to retry Spring WebClient to retry the operation based on the response? Spring WebClient - 如何根据响应延迟重试 header - Spring WebClient - how to retry with delay based on response header Spring WebClient - 如何在出现 HTTP 错误(4xx、5xx)的情况下访问响应正文? - Spring WebClient - how to access response body in case of HTTP errors (4xx, 5xx)? Spring webclient如何多次提取响应体 - Spring webclient how to extract response body multiple times 根据响应重试 WebClient - Retry the WebClient based on the response 如何在将响应返回给调用者时注销对 Spring WebFlux WebClient 请求的失败响应的正文? - How do I log out the body of a failed response to a Spring WebFlux WebClient request while returning the response to the caller? Java Spring WebClient如何从正文响应中获取属性并设置为给定的class? - Java Spring WebClient how to get atribute from body response and set to a given class? Spring WebClient 的自定义重试策略 - Custom Retry strategy for Spring WebClient 如何验证/处理 Spring WebClient 响应? - How to validate/process the Spring WebClient response? 如何在@Service 中模拟 Spring @Autowired WebClient 响应? - How to mock Spring @Autowired WebClient response in @Service?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM