2525import java .util .List ;
2626import java .util .Map ;
2727import java .util .concurrent .*;
28+ import java .util .concurrent .atomic .AtomicReference ;
2829import java .util .function .Consumer ;
2930import java .util .stream .Collectors ;
3031import java .util .stream .IntStream ;
@@ -715,6 +716,7 @@ public CompletableFuture<ClientBatchCheckResponse> batchCheck(
715716 var latch = new CountDownLatch (batchedChecks .size ());
716717
717718 var responses = new ConcurrentLinkedQueue <ClientBatchCheckSingleResponse >();
719+ var failure = new AtomicReference <Throwable >();
718720
719721 var override = new ConfigurationOverride ().addHeaders (options );
720722
@@ -735,26 +737,36 @@ public CompletableFuture<ClientBatchCheckResponse> batchCheck(
735737
736738 return api .batchCheck (configuration .getStoreId (), body , override );
737739 })
738- .handleAsync ((batchCheckResponseApiResponse , throwable ) -> {
739- Map <String , BatchCheckSingleResult > response =
740- batchCheckResponseApiResponse .getData ().getResult ();
741-
742- List <ClientBatchCheckSingleResponse > batchResults = new ArrayList <>();
743- response .forEach ((key , result ) -> {
744- boolean allowed = Boolean .TRUE .equals (result .getAllowed ());
745- ClientBatchCheckItem checkItem = correlationIdToCheck .get (key );
746- var singleResponse =
747- new ClientBatchCheckSingleResponse (allowed , checkItem , key , result .getError ());
748- batchResults .add (singleResponse );
749- });
750- return batchResults ;
751- })
752- .thenAccept (responses ::addAll )
753- .thenRun (latch ::countDown );
740+ .whenComplete ((batchCheckResponseApiResponse , throwable ) -> {
741+ try {
742+ if (throwable != null ) {
743+ failure .compareAndSet (null , throwable );
744+ return ;
745+ }
746+
747+ Map <String , BatchCheckSingleResult > response =
748+ batchCheckResponseApiResponse .getData ().getResult ();
749+
750+ List <ClientBatchCheckSingleResponse > batchResults = new ArrayList <>();
751+ response .forEach ((key , result ) -> {
752+ boolean allowed = Boolean .TRUE .equals (result .getAllowed ());
753+ ClientBatchCheckItem checkItem = correlationIdToCheck .get (key );
754+ var singleResponse =
755+ new ClientBatchCheckSingleResponse (allowed , checkItem , key , result .getError ());
756+ batchResults .add (singleResponse );
757+ });
758+ responses .addAll (batchResults );
759+ } finally {
760+ latch .countDown ();
761+ }
762+ });
754763
755764 try {
756765 batchedChecks .forEach (batch -> executor .execute (() -> singleBatchCheckRequest .accept (batch )));
757766 latch .await ();
767+ if (failure .get () != null ) {
768+ return CompletableFuture .failedFuture (failure .get ());
769+ }
758770 return CompletableFuture .completedFuture (new ClientBatchCheckResponse (new ArrayList <>(responses )));
759771 } catch (Exception e ) {
760772 return CompletableFuture .failedFuture (e );
0 commit comments