Error Handling with async.all()

I’m trying to determine the best way to handle errors when using the async Manager’s async.all().

Given this setup:

async()
  .all(
    () => doSomething(),
    () => another(),
    () => andAnother(),
    () => meToo()
  ).onException(( ex ) => {
    systemOutput(ex.getMessage(), true, true );
    return {};
  });

If multiple tasks error, the handler only seems to catch and log the first. If I don’t include onException(), any errors from the tasks aren’t reaching my application’s error handler.

Is there a better way to do this?

@lmajano can you chime in here please?

Ok, let’s start first with what this does internally. INternally, we convert all the incoming closures, to Futures and then send them off via the AllOf() method (CompletableFuture (Java Platform SE 8 )…-)

As per the docs:

Returns a new CompletableFuture that is completed when all of the given CompletableFutures complete. If any of the given CompletableFutures complete exceptionally, then the returned CompletableFuture also does so, with a CompletionException holding this exception as its cause. Otherwise, the results, if any, of the given CompletableFutures are not reflected in the returned CompletableFuture, but may be obtained by inspecting them individually. If no CompletableFutures are provided, returns a CompletableFuture completed with the value null.

So, you have to include the onException() or any of the methods that give you the result exception and handler, becuase, if ANY of those tasks fail, the exception will be sent to the handler ONLY if you attach it to the resulting future.

With that said, remember that each of the arguments can also be a future and you can attach an exception handler to EACH future as well.

async()
	.all(
		async().newFuture( () => doSomething() ).onException(),
		async().newFuture( () => doSomething() ).onException(),
		async().newFuture( () => doSomething() ).onException()
	);

You can also attach the same onException() to the same closure or udf. To reuse the exception handler. Againm, that’s if you want very picky exception handlign.

1 Like

Got it!

Thanks for explaining. Attaching an onException() to each future should work for me.

I just don’t like the idea of any exceptions getting swallowed. And while I hope that my code wouldn’t result in two exceptions during an async.all(), in cases when there are multiple API requests going out to external services, it seems like a possibility worth accounting for.