So i have started using ListenableFuture mainly due to improved code readability but I'm not quite settled on how to deal with exception propagation. (Btw, all in context of java 6 / android / many futures which ultimately can fail with more or less the same set of errors).
Regardless of ListenableFuture specifics my basic exception strategy (for my current project) is to reduce all exception to a small set of errors codes by anticipating some common fail scenarios upon which the user might be able to take some corrective action (e.g . check your wifi connection) while logging and letting the app crash for all others exceptions.
My basic usage is:
final ListenableFuture<Result> future = executor.submit(new Callable<Result>() {
@Override
public Result call() throws Exception {
Result result = doSomething();
// maybe do some extra processing;
return result;
}
});
Result doSomething() {
Result result = null;
try{
result = doSomething();
}
catch(InterestingException1 e) {
throw new MyCatchedException(e, Error.Code1);
}
catch(InterestingException2 e) {
throw new MyCatchedException(e, Error.Code2);
}
catch(Exception e) {
throw new MyCatchedException(e, Error.Bug);
}
return result;
}
Futures.addCallback(future, new FutureCallback<Result>() {
@Override
public void onSuccess(Result result) {
callSomeNonFurtureListener(result, null);
}
@Override
public void onFailure(Throwable throwable) {
callSomeNonFurtureListener(null, MyCatchedException);
}
}, MoreExecutors. ....);
The issue is with void onFailure(Throwable throwable) where essentially I lose my exception wrapper (the same with the Runnable callback version since I would need to call getCause on ExecutionException).
So currently I'm doing something like this:
MyCatchedException e = null;
if (throwable instanceof MyCatchedException)
e = (MyCatchedException) throwable;
else
e = new MyCatchedException(throwable, Error.Bug);
I'm using error codes because it seems less verbose to check a fixed set of error codes at the listener, specifically the errors that I'm interested about in the context of a particular Future completion task, then to have each error code be a standalone exception.
As specified in the title I'm seeking for opinions/alternatives about this.
tnx.
-Itai