【问题标题】:WebClient block is throwing nullPointerExceptionWebClient 块正在抛出 nullPointerException
【发布时间】:2020-03-24 04:25:43
【问题描述】:

我有以下代码从另一个服务中获取用户详细信息。

ParameterizedTypeReference<SuccessResponse<<User>> userTypeReference = new ParameterizedTypeReference<>() {}

User user = webClient.get()
                .uri("url")
                .retrieve()
                .onStatus(HttpStatus::is4xxClientError, response -> Mono.empty())
                .bodyToMono(userTypeReference)
                .onErrorResume(e -> Mono.empty())
                .doOnError(e -> logger.error("Error on fetching user details {}", e))
                .map(response -> response.getData())
                .block();

来自服务的响应如下所示:

{
  "status": "success",
  "data": {
      "name": "John",
      ...
  }
}

如果 data 元素不可用,则映射返回 null 并在 block() 上抛出 java.lang.NullPointerException: The mapper returned a null value 错误。

我知道我们可以在映射期间处理nullPointerException,如果数据对象为空,则返回new User 对象。但我不想得到一个空对象。有什么方法可以使用block() 获取空值?

【问题讨论】:

    标签: spring spring-boot spring-webflux


    【解决方案1】:

    Brian Clozel 的上述回答得到了很好的解释。我还找到了解决此问题的另一种方法。在这种情况下,我们可以通过过滤响应来避免NullPointerException

    User user = webClient.get()
                    .uri("url")
                    .retrieve()
                    .onStatus(HttpStatus::is4xxClientError, response -> Mono.empty())
                    .bodyToMono(userTypeReference)
                    .onErrorResume(e -> Mono.empty())
                    .doOnError(e -> logger.error("Error on fetching user details {}", e))
                    .filter(response -> !Objects.isNull(response.getData()))
                    .map(response -> response.getData())
                    .block();
    

    【讨论】:

    • 如果您想更明确地了解潜在的价值缺失,也可以使用blockOptional
    【解决方案2】:

    反应流规范 (Subscriber, rule 13) 禁止 null 元素,而这正是您的 map 运算符所做的:当您的响应的数据部分中没有提供用户时,它会返回 null 值。

    你应该在阻塞操作之后调用response.getData(),并对那里的null值做出反应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 2018-07-15
      • 2020-09-02
      • 2014-07-25
      • 2012-05-23
      • 1970-01-01
      • 2017-08-11
      相关资源
      最近更新 更多