![](/img/trans.png)
[英]Spring WebClient - how to access response body in case of HTTP errors (4xx, 5xx)?
[英]Java Spring Boot framework - WebClient logging 4xx/5xx body response
我是 Spring Boot 框架的 WebClient 的新手。 如何僅在錯誤時記錄 4xx/5xx 及其錯誤正文,但成功時,將clientResponse
作為String
返回,然后我們可以使用gson
進行序列化?
String postResponse =
post(
ENDPOINT,
token,
request,
Request.class);
Response response = gson.fromJson(postResponse, Response.class);
private String post(String endpoint, String token, Mono<?> requestBody, Class<?> requestBodyClass) {
WebClient.Builder webClientBuilder = WebClient.builder();
WebClient.RequestBodySpec requestBodySpec = webClientBuilder.build().post().uri(uri);
requestBodySpec.header(
"Authorization", BEARER_TOKEN_PREFIX + this.accessTokens.get(token));
return requestBodySpec
.header("Content-Type", HEADER_VALUE_CONTENT_TYPE)
.body(Mono.just(requestBody), requestBodyClass)
.retrieve()
.bodyToMono(String.class)
.block();
}
我可以提出以下建議:
private String post(String endpoint, String token, Mono<?> requestBody, Class<?> requestBodyClass) {
Mono<String> stringMono = WebClient.builder().build()
.post()
.uri(endpoint)
.body(BodyInserters.fromValue(requestBodyClass))
.exchange()
.flatMap(SomeServiceImpl::getResultAsStringOrLog4xx5xx);
//get the JSON from the Mono, but you might not want to block
}
(我省略了標題)
而問題的實際答案,請使用類似的方法執行日志記錄:
private static Mono<String> getResultAsStringOrLog4xx5xx(ClientResponse response) {
if (response.statusCode().is2xxSuccessful()) {
return response.bodyToMono(String.class);
} else if (response.statusCode().is5xxServerError()) {
Logger.error(); //up to you
} else {
//at this point, you can have your logic on error code
}
return
}
還有其他方法可以做到這一點,希望這可以幫助您入門。
另外,盡量不要在您的應用程序中使用 block() 。
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.