如何在Spring Webclient中处理HTTP状态代码

时间:2019-12-25 00:48:00

标签: spring spring-webclient

我在尝试调用远程服务时尝试进行简单的错误处理。该服务返回一个Map。我正在寻找的行为是:

  • HTTP 200->返回正文(Map<String, String>)。
  • HTTP 500->引发特定异常
  • HTTP 404->只需返回Null

这是我的代码:

private Map<String, String> loadTranslations(String languageTag) {
    try {
        WebClient webClient = WebClient.create(serviceUrl);
        Map<String, String> result = webClient.get()
            .uri("/translations/{language}", languageTag)
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .onStatus(httpStatus -> HttpStatus.NOT_FOUND.equals(httpStatus),
                clientResponse -> Mono.error(new MyServiceException(HttpStatus.NOT_FOUND)))
            .onStatus(HttpStatus::is5xxServerError, response -> Mono.error(new MyServiceException(response.statusCode())))
            .bodyToMono(Map.class)
            .block();

        return result;
    } catch (MyServiceException ex) {  // doesn't work as in reality it throws ReactiveException
        ....
    }
}

我不知道block()的结果如何返回NULL(或我可以解释为“ 404已收到”的内容)。这个想法是只在404上返回NULL并在500上抛出异常。

我尝试返回Mono.empty(),但是在那种情况下,result变量包含响应的主体作为Dictionary(我正在使用包含timestamp,{{1 }},path

我做错了什么?

谢谢

0 个答案:

没有答案