pawan kumar
pawan kumar

Reputation: 83

How to combine two async webclient call, assume if one call encountered some exception

I am using spring boot 2.x and making two async call using webclient, I am getting proper response with one call while other call encounter some exception. I want to zip both the responses together using zip method, but while using block with zip it throws exception and control flows to catch block. I want both the responses to be zipped along with exception in one or both. Please guide me how to do that.

Mono<BookResponse>  bookResponseMono =webClient.get()
           .uri("/getBooking/" + bookingId).headers(headers->headers.addAll(args) 
           .retrieve()
           .bodyToMono(BookResponse.class);// with proper responce
Mono<Address>  addressResponseMono =webClient.get()
           .uri("/getAddress/" + bookingId)
           .headers(headers->headers.addAll(args))
           .retrieve()
           .bodyToMono(Address.class);// encounter readtimeout exception

Tuple2<BookResponse, Address> resp = bookResponseMono.zipWith(addressResponseMono).block();// throws exception but 

I want to zip both the responses along with exception.

Upvotes: 1

Views: 1099

Answers (1)

pawan kumar
pawan kumar

Reputation: 83

onErrorResume worked for me for above problem.

bookResponseMono = webClient.get()
    .uri("/getBooking/" + bookingId)
    .headers(headers->headers.addAll(args))
    .retrieve()
    .bodyToMono(String.class)
    .onErrorResume(err -> {
        BookResponse bookResponse = new BookResponse();
        bookResponse.setError(setError(err));
        return Mono.just(setError(err));
    });

addressResponseMono = webClient.get()
    .uri("/getAddress/" + bookingId)
    .headers(headers -> headers.addAll(args))
    .retrieve()
    .bodyToMono(String.class)
    .onErrorResume(err -> {
        Address address = new Address();
        address.setError(setError(err));
        return Mono.just(setError(err));
    });

Zipping at last

bookAndAddressResponse = bookResponseMono
    .zipWith(addressResponseMono, BookAndAddressResponse::new)
    .block();

Upvotes: 2

Related Questions