如何在响应式Spring WebClient调用的错误部分抛出异常?

时间:2019-10-02 09:37:50

标签: reactive-programming project-reactor spring-webclient spring-reactive spring-reactor

如果发生错误,我希望通过以下方法引发自定义异常:

@Service
public class MyClass {

    private final WebClient webClient;

    public MatcherClient(@Value("${my.url}") final String myUrl) {
        this.webClient = WebClient.create(myUrl);
    }

    public void sendAsync(String request) {

        Mono<MyCustomResponse> result = webClient.post()
            .header(HttpHeaders.CONTENT_TYPE, "application/json")
            .body(BodyInserters.fromObject(request))
            .retrieve()
            .doOnError(throwable -> throw new CustomException(throwable.getMessage()))
            .subscribe(response -> log.info(response));

    }

}

我还设置了一个单元测试,期望抛出CustomException。不幸的是,测试失败,并且Exception被包装到Mono对象中。这里还有测试代码供参考:

@Test(expected = CustomException.class)
public void testSendAsyncRethrowingException() {
    MockResponse mockResponse = new MockResponse()
        .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
        .setResponseCode(500).setBody("Server error");
    mockWebServer.enqueue(mockResponse);

    matcherService.matchAsync(track);
}

我正在使用MockWebServer模拟测试中的错误。

那么,如果要使我的方法真正引发异常,该调用该如何实现doOnError或onError部分?

3 个答案:

答案 0 :(得分:1)

我建议公开一个反应式API,该API从Web客户端返回Mono<Void>,尤其是如果您将方法命名为“ sendAsync”。如果您必须阻止调用返回/失败,则它不是异步的。如果您想提供sendSync()的替代方案,则可以随时将其称为sendAsync().block()

对于异常的转换,可以使用专用的onErrorMap运算符。

对于测试而言,事实是,您不能100%使用纯命令性和同步结构(例如JUnit的Test(expected=?)批注)测试异步代码。 (尽管 some 反应性运算符不会引起并行性,所以这种测试有时有时可以正常工作)。

您还可以在此处使用.block()(测试是其中不太可能出现问题的罕见情况之一。)

但是如果我是你,我会养成使用StepVerifier中的reactor-test的习惯。举一个总结我的建议的例子:

@Service
public class MyClass {

    private final WebClient webClient;

    public MatcherClient(@Value("${my.url}") final String myUrl) {
        this.webClient = WebClient.create(myUrl);
    }

    public Mono<MyCustomResponse> sendAsync(String request) {
        return webClient.post()
            .header(HttpHeaders.CONTENT_TYPE, "application/json")
            .body(BodyInserters.fromObject(request))
            .retrieve()
            .onErrorMap(throwable -> new CustomException(throwable.getMessage()))
            //if you really need to hardcode that logging
            //(can also be done by users who decide to subscribe or further add operators)
            .doOnNext(response -> log.info(response));
    }
}

和测试:

@Test(expected = CustomException.class)
public void testSendAsyncRethrowingException() {
    MockResponse mockResponse = new MockResponse()
        .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
        .setResponseCode(500).setBody("Server error");
    mockWebServer.enqueue(mockResponse);

    //Monos are generally lazy, so the code below doesn't trigger any HTTP request yet
    Mono<MyCustomResponse> underTest = matcherService.matchAsync(track);

    StepVerifier.create(underTest)
    .expectErrorSatisfies(t -> assertThat(t).isInstanceOf(CustomException.class)
        .hasMessage(throwable.getMessage())
    )
    .verify(); //this triggers the Mono, compares the
               //signals to the expectations/assertions and wait for mono's completion

}

答案 1 :(得分:0)

<块引用>

WebClient 中的retrieve() 方法抛出WebClientResponseException 每当收到状态代码为 4xx 或 5xx 的响应时。

1.您可以使用 onStatus() 方法自定义异常

public Mono<JSONObject> listGithubRepositories() {
 return webClient.get()
        .uri(URL)
        .retrieve()
        .onStatus(HttpStatus::is4xxClientError, clientResponse ->
            Mono.error(new MyCustomClientException())
        )
        .onStatus(HttpStatus::is5xxServerError, clientResponse ->
            Mono.error(new MyCustomServerException())
        )
        .bodyToMono(JSONObject.class);
}

2.通过检查响应状态抛出自定义异常

   Mono<Object> result = webClient.get().uri(URL).exchange().log().flatMap(entity -> {
        HttpStatus statusCode = entity.statusCode();
        if (statusCode.is4xxClientError() || statusCode.is5xxServerError())
        {
            return Mono.error(new Exception(statusCode.toString()));
        }
        return Mono.just(entity);
    }).flatMap(clientResponse -> clientResponse.bodyToMono(JSONObject.class))

参考: https://www.callicoder.com/spring-5-reactive-webclient-webtestclient-examples/

答案 2 :(得分:-1)

我不再使用doOnError,而是订阅方法也接受错误使用者:

Mono<MyCustomResponse> result = webClient.post()
            .header(HttpHeaders.CONTENT_TYPE, "application/json")
            .body(BodyInserters.fromObject(request))
            .retrieve()
            .subscribe(response -> log.info(response),
                       throwable -> throw new CustomException(throwable.getMessage()));

该文档对您有很大帮助:https://projectreactor.io/docs/core/release/reference/index.html#_error_handling_operators