问题描述
我是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
}
还有其他方法可以实现,希望可以帮助您入门。
此外,请尽量不要在应用程序中阻止()。
谢谢