Java Spring WebClient根据状态代码嵌套Mono
使用WebClient,我想根据HTTP状态代码分别处理ClientResponse。下面是top doOnSuccess中使用的两个新subscribe()方法。如何将这些嵌套的Mono传送到WebClient的Mono链?也就是说,如何消除内在的monosJava Spring WebClient根据状态代码嵌套Mono,java,spring-webflux,spring-reactive,Java,Spring Webflux,Spring Reactive,使用WebClient,我想根据HTTP状态代码分别处理ClientResponse。下面是top doOnSuccess中使用的两个新subscribe()方法。如何将这些嵌套的Mono传送到WebClient的Mono链?也就是说,如何消除内在的monos webClient.post() .uri( soapServiceUrl ) .contentType(MediaType.TEXT_XML) //.body(Mo
webClient.post()
.uri( soapServiceUrl )
.contentType(MediaType.TEXT_XML)
//.body(Mono.just(req), String.class )
.body( Mono.just(getCountryRequest) , GetCountryRequest.class )
.exchange()
.filter( (ClientResponse response) -> { return true; } )
.doOnSuccess( (ClientResponse response) -> {
//nested mono 1
if( response.statusCode().is5xxServerError() ){
response.toEntity(String.class).doOnSuccess(
error -> {
System.out.println("error : "+ error);
}).subscribe();
}
//nested mono 2
if( response.statusCode().is2xxSuccessful() ){
response.toEntity(GetCountryResponse.class).doOnSuccess(
getCountryResponse -> {
System.out.println("success : "+ getCountryResponse.getBody().getCountry().getCapital());
}).subscribe();
}
})
.doOnError( (Throwable error) -> {
System.out.println( "getCountryResponse.error : "+ error );
})
.subscribe();
Webclient的
retrieve()
方法有更好的方法来处理错误代码
我会这样做:
webClient.post()
.uri( soapServiceUrl )
.contentType(MediaType.TEXT_XML)
//.body(Mono.just(req), String.class )
.body( Mono.just(getCountryRequest) , GetCountryRequest.class )
.retrieve()
.onStatus(
HttpStatus::isError,
clientResponse ->
clientResponse
//get the error response body as a string
.bodyToMono(String.class)
//flatmap the errorResponseBody into a new error signal
.flatMap(
errorResponseBody ->
Mono.error(
new ResponseStatusException(
clientResponse.statusCode(),
errorResponseBody))))
//get success response as Mono<GetCountryResponse>
.bodyToMono(GetCountryResponse.class)
.doOnSuccess( (GetCountryResponse response) ->
System.out.println("success : " +
response.getBody().getCountry().getCapital()))
//Response errors will now be logged below
.doOnError(ResponseStatusException.class, error -> {
System.out.println( "getCountryResponse.error : "+ error );
})
.subscribe();
webClient.post()
.uri(soapServiceUrl)
.contentType(MediaType.TEXT_XML)
//.body(Mono.just(req),String.class)
.body(Mono.just(getCountryRequest),getCountryRequest.class)
.retrieve()
onStatus先生(
HttpStatus::iSeries错误,
clientResponse->
阴蒂反应
//以字符串形式获取错误响应正文
.bodyToMono(String.class)
//将errorResponseBody平面映射为新的错误信号
.平面图(
errorResponseBody->
一元误差(
新的ResponseStatusException(
clientResponse.statusCode(),
errorResponseBody)))
//以Mono的形式获得成功响应
.BodyToNo(GetCountryResponse.class)
.doOnSuccess((GetCountryResponse响应)->
System.out.println(“成功:”+
response.getBody().getCountry().getCapital())
//响应错误现在将记录在下面
.doon错误(ResponseStatusException.class,错误->{
System.out.println(“getCountryResponse.error:+error”);
})
.subscribe();