-1

When working with CompletableFuture any potential errors from computing the value are exposed via the get() method throwing an ExecutionException. I can of course log this exception at the time of calling this method, but it would be misleading as this exception may have happened at a completely different time from the current.

In short, I would like information on when the ExecutionException occurred. Is there any elegant solution to this ?

peterh
  • 18,404
  • 12
  • 87
  • 115
  • Why not catch, log and rethrow the exception inside the Runnable/Callable? – assylias Apr 02 '22 at 08:25
  • @assylias: I'm writing an abstract class for general use. I cannot log anything in the actual computation but I can certainly _wrap_ the computation in my own Exception class which can then hold an Instant. However, it all gets somewhat complex. I see this as a general requirement for anyone using FutureTasks/CompletableFutures so I was hoping that there would be some JDK feature that I've overlooked. In short, I don't understand why I cannot find an Instant in `ExecutionException`. Wouldn't everyone want that? (given that ExecutionException by definition holds errors from a _past_ event). – peterh Apr 02 '22 at 09:26
  • 1
    To be honest: no. In most cases, the time an exception occurred is not relevant. The whole point of asynchronous execution is that the caller wants it executed in the background, but does not care exactly when it happens. – VGR Apr 02 '22 at 12:49
  • @Vgr: I agree, but this is not exceptions in general. Knowing the time when this type of exceptions, ExecutionExceptions, happens is definitely relevant. If you log it at the time where such exception happens to be exposed to you then it will be wrong. Consider someone reading that log. Very confusing. There may be minutes - or in my case potentially hours - between when the exception is exposed and when it really occurred. – peterh Apr 02 '22 at 13:24
  • 1
    Why should the time of the `ExecutionException` ever be relevant? The `ExecutionException` is created inside the `get()` method. You might actually mean the time when the *wrapped* exception has been created, but `CompletableFuture` does not know this. – Holger Apr 04 '22 at 13:35

2 Answers2

0

Use callback methods, i.e. exceptionally, whenComplete or handle, which pass a Throwable and a result.

-2

Try to wrap execution code into try-catch, which you passed to CompletableFuture.