I have classes called say CalculationOutcome
and FileHashOutcome
. Their constructors have (ActualResult, Throwable)
arguments, and at the end of a chain of CompletionStage
s I have handle(XxxOutcome::new)
.
It might make intentions clearer and save some boilerplate if I could write say PossiblyWithError<FileHash>
.
Edit: People asking for example code...
class FileHashOutcome {
private final String hash;
private final Throwable throwable;
FileHashOutcome(String hash, Throwable throwable){
// Usual assignments
}
}
CompletionStage<FileHashOutcome> future =
SomeExternalLibrary.calculateHash(file)
// ...It's a CompletionStage<String> at this stage...
.handle(FileHashOutcome::new);
// Then I pass `future` to a service that
// will execute it and pass back the result asynchronously
To be specific, it's within an Akka actor, and I'm asking the infrastructure to pipe the result back into the actor as a message.
Edit: suggestions that CompletableFuture
might do the job... Yes, good point, it represents exactly what needs to be represented. And it's a bit of a code smell to implement your own rough-and-ready future then wrap it in the java8 future.
There are some hoops to jump through depending on whether you have access to the "envelope" of the future. If you're inside a thenApply
then you're "inside" the envelope and you don't know it. And the Akka infrastructure "throws away" the envelope and only returns the result (and it returns nothing if there was an exception, which is one of the main reasons why I wanted to catch and wrap that exception at the end of the CompletionStage
chain). Of course, since I created the CompletionStage, I could hold onto it in a member variable until the infrastructure nudged me that it had completed.
Per @marstran, the usual name for this class is Try.
Scala has such a class in its standard library: https://www.scala-lang.org/api/2.9.3/scala/util/Try.html
The same can be done in Java, but it is not a part of the standard library: https://dzone.com/articles/why-try-better-exception-handling-in-java-with-try
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With