SpringWebClient根据状态代码嵌套

ua4mk5z4  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(337)

使用webclient,我想根据http状态码分别处理clientresponse。下面是top doonsuccess中使用的两个新subscribe()方法。如何将这些嵌套的mono带到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();
0md85ypi

0md85ypi1#

网络客户的 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();

相关问题