2

EDIT: The core issue to this is handling errors from the Mono and converting to a new object type so I can later map as needed. Right now any unhandled errors will stop the stream. If I use onErrorReturn, then I must return the original response type (UpdateResponse), but I want to return a new type with the error details. I could use onErrorResume and return Mono.empty() but again, I want to capture the error details.

I am looking to utilize Spring's Reactive WebClient to make parallel calls to an external service which will update a user given a list of IDs and then collect any errors / successes into a single response I can then return to the caller. All the error handling I've seen so far, doesn't allow me to map the data to a new response, so unsure how to handle this.

// This is the class where I want to collect and map successes/errors to a new response object
public class UpdateUserService {
  private final UpdateUserClient updateUserClient;
  
  public Mono<UpdateUserResponse> updateUser(List<Long> userIds, UpdateUserRequest request) {

    // Parallel calls to updateUserClient
    Mono<UpdateUserResponse> resp = Flux.fromIterable(userIds)
      .flatMap(userId -> updateUserClient.updatUser(userId, request))
      // How to maps successes and handle errors here to UpdateUserResponse?
      ...

      return resp;
      
  }
}

// Supporting classes
public class UpdateUserResponse {
    List<UpdateUserResult> results;
}

public class UpdateUserResult {
    Long id;
    Boolean success;
    String message;
}

public class UpdateUserClient {
    private final WebClient webClient;
    private final String path;


    public Mono<UpdateResponse> updatUser(Long userId, UpdateUserRequest request) {
        return webClient.put()
            .uri(uriBuilder -> uriBuilder
                .path(path)
                .queryParam("userId", userID)
                .build())
            .body(request, UpdateUserRequest.class)
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .bodyToMono(UpdateResponse.class);  // UpdateResponse just contains a success boolean
    }
}
Steve W
  • 81
  • 5

0 Answers0