Spring WebClient根据状态码嵌套Mono

Spring WebClient nested Mono according to status codes

使用WebClient 我想根据HTTP 状态代码单独处理ClientResponse。下面你会看到在 doOnSuccess 中使用了两个新的 subscribe() 方法。如何将那些嵌套的 Monos 携带到 WebClient 的 Mono 链上?也就是如何消除inner monos。

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();