【问题标题】:Java Spring Boot framework - WebClient logging 4xx/5xx body responseJava Spring Boot 框架 - WebClient 记录 4xx/5xx 正文响应
【发布时间】:2021-02-10 08:37:14
【问题描述】:

我是 Spring Boot 框架的 WebClient 的新手。如何仅在错误时记录带有错误主体的 4xx/5xx,但在成功时将clientResponse 作为String 返回,我们以后可以使用gson 对其进行序列化?


String postResponse =
        post(
            ENDPOINT,
            token,
            request,
            Request.class);

Response response = gson.fromJson(postResponse, Response.class);

    private String post(String endpoint, String token, Mono<?> requestBody, Class<?> requestBodyClass) {

      WebClient.Builder webClientBuilder = WebClient.builder();

      WebClient.RequestBodySpec requestBodySpec = webClientBuilder.build().post().uri(uri);
      requestBodySpec.header(
          "Authorization", BEARER_TOKEN_PREFIX + this.accessTokens.get(token));

      return requestBodySpec
        .header("Content-Type", HEADER_VALUE_CONTENT_TYPE)
        .body(Mono.just(requestBody), requestBodyClass)
        .retrieve()
        .bodyToMono(String.class)
        .block();
    }

【问题讨论】:

    标签: java spring-boot spring-webclient


    【解决方案1】:

    我可以提出类似的建议:

        private String post(String endpoint, String token, Mono<?> requestBody, Class<?> requestBodyClass) {
            Mono<String> stringMono = WebClient.builder().build()
                    .post()
                    .uri(endpoint)
                    .body(BodyInserters.fromValue(requestBodyClass))
                    .exchange()
                    .flatMap(SomeServiceImpl::getResultAsStringOrLog4xx5xx);
            
            //get the JSON from the Mono, but you might not want to block
        }
    
    

    (我省略了标题)

    对于问题的实际答案,请使用类似的方法执行日志记录:

    private static Mono<String> getResultAsStringOrLog4xx5xx(ClientResponse response) {
            if (response.statusCode().is2xxSuccessful()) {
                return response.bodyToMono(String.class);
            } else if (response.statusCode().is5xxServerError()) {
                Logger.error(); //up to you
            } else {
    //at this point, you can have your logic on error code
            }
            return
        }
    

    还有其他方法可以做到这一点,希望这可以帮助您入门。

    另外,尽量不要在你的应用程序中使用 block()。

    谢谢

    【讨论】:

    • 为什么不使用block() ?我们调用它的端点期望我们块同步调用它。
    • 只是一个建议。反应式编程的全部目的不是阻塞。但如果你有你的用例,请随意。只是一个建议。我的回答主要是帮助记录错误
    • 谢谢,但是有了block(),exchange() 和flatMap() 会是什么样子?
    • 只要返回 stringMono.block();如果是您的用例,请在您的 post 方法上使用:)
    • 谢谢,我仍然无法弄清楚如何在 4xx/5xx 错误上记录 response.body。这正是我想要记录的内容。
    猜你喜欢
    • 2020-06-29
    • 2018-05-25
    • 2016-09-28
    • 2021-05-21
    • 2020-08-26
    • 2018-10-17
    • 2021-07-21
    • 2020-04-05
    相关资源
    最近更新 更多