如何在 Spring WebClient 构建器实例中设置 onStatus
How to set onStatus in Spring WebClient builder instance
我有很多使用 Spring 的 WebClient 中的 onStatus API 的方法:
@Override
public Mono<Accommodation> createAccommodation(CreateAccommodation create) {
return webClient
.post()
.contentType(APPLICATION_JSON)
.bodyValue(create)
.retrieve()
.onStatus(HttpStatus::isError,
clientResponse -> clientResponse
.bodyToMono(ApiErrorResponse.class)
.flatMap(errorResponse -> Mono.error(new ResponseStatusException(
HttpStatus.valueOf(errorResponse.getStatus()),
errorResponse.getMessage()
))))
.bodyToMono(Accommodation.class);
}
我想做的是避免在每次 WebClient 调用中都必须使用 "onStatus"。
有没有办法在构建 WebClient 实例时设置它?你能举一些例子吗?
这是我的 WebClient 实例:
public AccommodationServiceClientImpl(WebClient.Builder builder) {
this.webClient = builder
.baseUrl("lb://accommodation-service/api/v1/accommodations")
.build();
}
找到解决方案:ExchangeFilterFunction.ofResponseProcessor 似乎是我要找的。
@Configuration
public class WebClientConfig {
@Bean
@LoadBalanced
public WebClient.Builder webClientBuilder(){
return WebClient
.builder()
.filter(ExchangeFilterFunction.ofResponseProcessor(this::renderApiErrorResponse));
}
private Mono<ClientResponse> renderApiErrorResponse(ClientResponse clientResponse) {
if(clientResponse.statusCode().isError()){
return clientResponse.bodyToMono(ApiErrorResponse.class)
.flatMap(apiErrorResponse -> Mono.error(new ResponseStatusException(
clientResponse.statusCode(),
apiErrorResponse.getMessage()
)));
}
return Mono.just(clientResponse);
}
}
我有很多使用 Spring 的 WebClient 中的 onStatus API 的方法:
@Override
public Mono<Accommodation> createAccommodation(CreateAccommodation create) {
return webClient
.post()
.contentType(APPLICATION_JSON)
.bodyValue(create)
.retrieve()
.onStatus(HttpStatus::isError,
clientResponse -> clientResponse
.bodyToMono(ApiErrorResponse.class)
.flatMap(errorResponse -> Mono.error(new ResponseStatusException(
HttpStatus.valueOf(errorResponse.getStatus()),
errorResponse.getMessage()
))))
.bodyToMono(Accommodation.class);
}
我想做的是避免在每次 WebClient 调用中都必须使用 "onStatus"。
有没有办法在构建 WebClient 实例时设置它?你能举一些例子吗?
这是我的 WebClient 实例:
public AccommodationServiceClientImpl(WebClient.Builder builder) {
this.webClient = builder
.baseUrl("lb://accommodation-service/api/v1/accommodations")
.build();
}
找到解决方案:ExchangeFilterFunction.ofResponseProcessor 似乎是我要找的。
@Configuration
public class WebClientConfig {
@Bean
@LoadBalanced
public WebClient.Builder webClientBuilder(){
return WebClient
.builder()
.filter(ExchangeFilterFunction.ofResponseProcessor(this::renderApiErrorResponse));
}
private Mono<ClientResponse> renderApiErrorResponse(ClientResponse clientResponse) {
if(clientResponse.statusCode().isError()){
return clientResponse.bodyToMono(ApiErrorResponse.class)
.flatMap(apiErrorResponse -> Mono.error(new ResponseStatusException(
clientResponse.statusCode(),
apiErrorResponse.getMessage()
)));
}
return Mono.just(clientResponse);
}
}