我正在使用spring webflux的webclient,如下所示:
WebClient.create()
.post()
.uri(url)
.syncBody(body)
.accept(MediaType.APPLICATION_JSON)
.headers(headers)
.exchange()
.flatMap(clientResponse -> clientResponse.bodyToMono(tClass));
运作良好。 我现在想要处理来自我正在调用的Web服务的错误(Ex 500内部错误)。通常我会在" stream"上添加一个doOnError。并且isu Throwable来测试状态代码,
但我的问题是我想获得webservice提供的正文,因为它为我提供了一条我想要使用的消息。
我希望无论发生什么事情都要做flatMap,并测试自己的状态代码以反序列化或不反复身体。
答案 0 :(得分:9)
我更喜欢使用ClientResponse提供的方法来处理http错误并引发异常:
WebClient.create()
.post()
.uri( url )
.body( bodyObject == null ? null : BodyInserters.fromValue( bodyObject ) )
.accept( MediaType.APPLICATION_JSON )
.headers( headers )
.exchange()
.flatMap( clientResponse -> {
//Error handling
if ( clientResponse.statusCode().isError() ) { // or clientResponse.statusCode().value() >= 400
return clientResponse.createException().flatMap( Mono::error );
}
return clientResponse.bodyToMono( clazz )
} )
//You can do your checks: doOnError (..), onErrorReturn (..) ...
...
实际上,它与DefaultWebClient的DefaultResponseSpec中用于处理错误的逻辑相同。 DefaultResponseSpec是ResponseSpec的实现,如果我们进行了retrieve()而不是exchange()的话,我们将拥有该响应。
答案 1 :(得分:5)
我这样做:
Mono<ClientResponse> responseMono = requestSpec.exchange()
.doOnNext(response -> {
HttpStatus httpStatus = response.statusCode();
if (httpStatus.is4xxClientError() || httpStatus.is5xxServerError()) {
throw new WebClientException(
"ClientResponse has erroneous status code: " + httpStatus.value() +
" " + httpStatus.getReasonPhrase());
}
});
然后:
responseMono.subscribe(v -> { }, ex -> processError(ex));
答案 2 :(得分:5)
我们没有onStatus()
吗?
public Mono<Void> cancel(SomeDTO requestDto) {
return webClient.post().uri(SOME_URL)
.body(fromObject(requestDto))
.header("API_KEY", properties.getApiKey())
.retrieve()
.onStatus(HttpStatus::isError, response -> {
logTraceResponse(log, response);
return Mono.error(new IllegalStateException(
String.format("Failed! %s", requestDto.getCartId())
));
})
.bodyToMono(Void.class)
.timeout(timeout);
}
并且:
public static void logTraceResponse(Logger log, ClientResponse response) {
if (log.isTraceEnabled()) {
log.trace("Response status: {}", response.statusCode());
log.trace("Response headers: {}", response.headers().asHttpHeaders());
response.bodyToMono(String.class)
.publishOn(Schedulers.elastic())
.subscribe(body -> log.trace("Response body: {}", body));
}
}
答案 3 :(得分:4)
请注意,在写入此内容时,5xx错误不再导致基础Netty层出现异常。见https://github.com/spring-projects/spring-framework/commit/b0ab84657b712aac59951420f4e9d696c3d84ba2
答案 4 :(得分:4)
您也可以这样做
return webClient.getWebClient()
.post()
.uri("/api/Card")
.body(BodyInserters.fromObject(cardObject))
.exchange()
.flatMap(clientResponse -> {
if (clientResponse.statusCode().is5xxServerError()) {
clientResponse.body((clientHttpResponse, context) -> {
return clientHttpResponse.getBody();
});
return clientResponse.bodyToMono(String.class);
}
else
return clientResponse.bodyToMono(String.class);
});
阅读本文以获取更多示例link,我发现在遇到类似的错误处理问题时会有所帮助
答案 5 :(得分:3)
我们终于明白了发生了什么: 默认情况下,Netty的httpclient(HttpClientRequest)配置为服务器错误(响应5XX)而不是客户端错误(4XX)失败,这就是它总是发出异常的原因。
我们所做的是扩展AbstractClientHttpRequest和ClientHttpConnector,以便按照需要的方式配置httpclient行为,当我们调用WebClient时,我们使用自定义ClientHttpConnector:
WebClient.builder().clientConnector(new CommonsReactorClientHttpConnector()).build();
答案 6 :(得分:2)
我刚刚遇到过类似的情况,我发现webClient即使收到4xx / 5xx响应也不会抛出任何异常。就我而言,我首先使用webclient进行调用以获取响应,如果该响应返回2xx响应,则从响应中提取数据并将其用于第二次调用。如果第一个电话收到非2xx响应,则抛出异常。因为它没有引发异常,所以当第一个调用失败而第二个调用仍继续进行时。所以我所做的是
return webClient.post().uri("URI")
.header(HttpHeaders.CONTENT_TYPE, "XXXX")
.header(HttpHeaders.ACCEPT, "XXXX")
.header(HttpHeaders.AUTHORIZATION, "XXXX")
.body(BodyInserters.fromObject(BODY))
.exchange()
.doOnSuccess(response -> {
HttpStatus statusCode = response.statusCode();
if (statusCode.is4xxClientError()) {
throw new Exception(statusCode.toString());
}
if (statusCode.is5xxServerError()) {
throw new Exception(statusCode.toString());
}
)
.flatMap(response -> response.bodyToMono(ANY.class))
.map(response -> response.getSomething())
.flatMap(something -> callsSecondEndpoint(something));
}
答案 7 :(得分:1)
我这样做是得到了错误正文:
webClient
...
.retrieve()
.onStatus(HttpStatus::isError, response -> response.bodyToMono(String.class) // error body as String or other class
.flatMap(error -> Mono.error(new RuntimeException(error)))) // throw a functional exception
.bodyToMono(MyResponseType.class)
.block();
答案 8 :(得分:0)
WebClient 中的retrieve() 方法抛出WebClientResponseException 每当收到状态代码为 4xx 或 5xx 的响应时。
您可以通过检查响应状态代码来处理异常。
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/
答案 9 :(得分:0)
我偶然发现了这个,所以我想我不妨发布我的代码。
我所做的是创建一个全局处理程序,它处理来自 Web 客户端的请求和响应错误。这是在 Kotlin 中,但当然可以轻松转换为 Java。这扩展了默认行为,因此您可以确保在客户处理之上获得所有自动配置。
正如您所看到的,这并没有真正做任何自定义的事情,它只是将 Web 客户端错误转换为相关响应。对于响应错误,代码和响应主体被简单地传递给客户端。对于当前的请求错误,它只处理连接问题,因为这是我所关心的(目前),但正如您所见,它可以轻松扩展。
@Configuration
class WebExceptionConfig(private val serverProperties: ServerProperties) {
@Bean
@Order(-2)
fun errorWebExceptionHandler(
errorAttributes: ErrorAttributes,
resourceProperties: ResourceProperties,
webProperties: WebProperties,
viewResolvers: ObjectProvider<ViewResolver>,
serverCodecConfigurer: ServerCodecConfigurer,
applicationContext: ApplicationContext
): ErrorWebExceptionHandler? {
val exceptionHandler = CustomErrorWebExceptionHandler(
errorAttributes,
(if (resourceProperties.hasBeenCustomized()) resourceProperties else webProperties.resources) as WebProperties.Resources,
serverProperties.error,
applicationContext
)
exceptionHandler.setViewResolvers(viewResolvers.orderedStream().collect(Collectors.toList()))
exceptionHandler.setMessageWriters(serverCodecConfigurer.writers)
exceptionHandler.setMessageReaders(serverCodecConfigurer.readers)
return exceptionHandler
}
}
class CustomErrorWebExceptionHandler(
errorAttributes: ErrorAttributes,
resources: WebProperties.Resources,
errorProperties: ErrorProperties,
applicationContext: ApplicationContext
) : DefaultErrorWebExceptionHandler(errorAttributes, resources, errorProperties, applicationContext) {
override fun handle(exchange: ServerWebExchange, throwable: Throwable): Mono<Void> =
when (throwable) {
is WebClientRequestException -> handleWebClientRequestException(exchange, throwable)
is WebClientResponseException -> handleWebClientResponseException(exchange, throwable)
else -> super.handle(exchange, throwable)
}
private fun handleWebClientResponseException(exchange: ServerWebExchange, throwable: WebClientResponseException): Mono<Void> {
exchange.response.headers.add("Content-Type", "application/json")
exchange.response.statusCode = throwable.statusCode
val responseBodyBuffer = exchange
.response
.bufferFactory()
.wrap(throwable.responseBodyAsByteArray)
return exchange.response.writeWith(Mono.just(responseBodyBuffer))
}
private fun handleWebClientRequestException(exchange: ServerWebExchange, throwable: WebClientRequestException): Mono<Void> {
if (throwable.rootCause is ConnectException) {
exchange.response.headers.add("Content-Type", "application/json")
exchange.response.statusCode = HttpStatus.BAD_GATEWAY
val responseBodyBuffer = exchange
.response
.bufferFactory()
.wrap(ObjectMapper().writeValueAsBytes(customErrorWebException(exchange, HttpStatus.BAD_GATEWAY, throwable.message)))
return exchange.response.writeWith(Mono.just(responseBodyBuffer))
} else {
return super.handle(exchange, throwable)
}
}
private fun customErrorWebException(exchange: ServerWebExchange, status: HttpStatus, message: Any?) =
CustomErrorWebException(
Instant.now().toString(),
exchange.request.path.value(),
status.value(),
status.reasonPhrase,
message,
exchange.request.id
)
}
data class CustomErrorWebException(
val timestamp: String,
val path: String,
val status: Int,
val error: String,
val message: Any?,
val requestId: String,
)