首页 > 解决方案 > Spring reactor - 如何正确抛出异常?

问题描述

我有这个代码:

   public void createImage(Image image) {
        tokenProvider.getAccessToken()
                .flatMap(accessToken -> restCllent.decodeColour(url, accessToken.getToken())
                    .flatMap(colour -> restClient.createImage(url, accessToken.getToken())))
                .subscribe();
  }

在函数 decodeColour 我有这个调用外部服务的代码:

    public Mono<Colour> decodeColour(String path, String token) {
        log.info("Executing GET request to {}", path);
        return webClient
            .get()
            .uri(path)
            .header(HttpHeaders.AUTHORIZATION, String.format(TOKEN_BEARER, token))
            .retrieve()
            .bodyToMono(Colour.class)
            .onErrorResume(e -> Mono.error(new RuntimeException("Error occurred during colour decoding: " + e.getMessage())));
    }

当外部服务返回例如 401 时,我在 onErrorResume() 中处理了它,我只想抛出 RuntimeException。在“createImage(Image image)”函数上面的代码中,如果 decodeColour() 中发生错误,我如何强制代码只抛出 RuntimeException?如果我这样离开它,我会得到 ErrorCallbackNotImplemented: RuntimeException: Error occurred during color coding。如果我添加一些像doOnError这样的错误回调,它只是处理错误,但我想编程抛出我的RuntimeException。这样做对我很重要。

标签: javaspringreactive-programmingspring-webfluxproject-reactor

解决方案


推荐阅读