为 Spring Web 客户端添加异常处理程序

Add Exception handler for Spring Web Client

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

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

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

如果我在由于 SSL 凭据导致连接失败的上下文中理解你的问题,那么你应该会在 REST 响应中看到连接异常本身。 您可以通过在 WebClient.ResponseSpec#onStatus 上获得的 Flux 结果来处理该异常。 #onStatus 的文档说:

Register a custom error function that gets invoked when the given HttpStatus predicate applies. The exception returned from the function will be returned from bodyToMono(Class) and bodyToFlux(Class). By default, an error handler is register that throws a WebClientResponseException when the response status code is 4xx or 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);

希望对您有所帮助。