首页 > 解决方案 > Spring WebClient 根据状态码嵌套 Mono

问题描述

使用 WebClient 我想根据 HTTP 状态码分别处理 ClientResponse。下面你会看到在顶部 doOnSuccess 中使用的两个新的 subscribe() 方法。如何将那些嵌套的 Monos 带到 WebClient 的 Mono 链中?也就是说,如何消除内在的单声道。

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

标签: javaspring-webfluxspring-reactive

解决方案


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


推荐阅读