为Spring Web Client添加异常处理程序

时间:2018-07-02 15:21:30

标签: spring spring-webflux

我将此代码用于REST API请求。

WebClient.Builder builder = WebClient.builder().baseUrl(gatewayUrl);
ClientHttpConnector httpConnector = new ReactorClientHttpConnector(opt -> opt.sslContext(sslContext));
builder.clientConnector(httpConnector);

如何添加连接异常处理程序?我想实现一些自定义逻辑?这个功能容易实现吗?

1 个答案:

答案 0 :(得分:5)

如果在因SSL凭证而导致连接失败的情况下理解了您的问题,那么您应该在REST响应中看到连接异常本身。 您可以通过WebClient.ResponseSpec#onStatus上的Flux结果来处理该异常。 #onStatus的文档说:

  

注册一个自定义错误函数,该函数将在给定给定值时被调用   HttpStatus谓词适用。从函数返回的异常   将从bodyToMono(Class)bodyToFlux(Class)返回。通过   默认情况下,错误处理程序是抛出   WebClientResponseException,如果响应状态代码为 4xx 或    5xx

看看this example

Mono<Person> result = client.get()
            .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .onStatus(HttpStatus::is4xxServerError, response -> ...) // This is in the docs there but is wrong/fatfingered, should be is4xxClientError
            .onStatus(HttpStatus::is5xxServerError, response -> ...)
            .bodyToMono(Person.class);

类似地,对于您的问题,连接错误应该在调用完成后显现出来,您可以自定义在响应管道中如何传播它:

Mono<Person> result = client.get()
            .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .onStatus(HttpStatus::is4xxClientError, response -> {
                 ... Code that looks at the response more closely...
                 return Mono.error(new MyCustomConnectionException());
             })
            .bodyToMono(Person.class);

希望有帮助。