问题
There is pretty heavy use of io.vertx.core.Future
in the vertx ecosystem:
https://vertx.io/docs/apidocs/io/vertx/core/Future.html
An example of using Vertx Future
is here:
private Future<Void> prepareDatabase() {
Future<Void> future = Future.future();
dbClient = JDBCClient.createShared(vertx, new JsonObject(...));
dbClient.getConnection(ar -> {
if (ar.failed()) {
LOGGER.error("Could not open a database connection", ar.cause());
future.fail(ar.cause()); // here
return;
}
SQLConnection connection = ar.result();
connection.execute(SQL_CREATE_PAGES_TABLE, create -> {
connection.close();
if (create.failed()) {
future.fail(create.cause()); // here
} else {
future.complete();
}
});
});
return future;
}
I was under the impression that io.vertx.core.Future
had something to do with java.util.concurrent.Future
, but it appears that it doesn't. As you can see the way to tell a Vertx future to fail is to call it's fail() method.
On the other hand, we have CompletableFuture which is an implementation of the java.util.concurrent.Future
interface:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html
I don't see a fail method on the CompletableFuture, I only see "resolve()".
So my guess is that the only way to fail a CompletableFuture is to throw an Exception?
CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("fail this future");
return "This would be the success result";
});
besides throwing an error, is there a way to "fail" a CompletableFuture? In other words, using a Vertx Future, we just call f.fail(), but what about with a CompletableFuture?
回答1:
CompletableFuture
encourages you to throw exceptions from supplyAsync()
method to describe failures.
As mentioned in the comments, there's also completeExceptionally()
method, which you can use in case you have a Future
at hand, and would like to fail it.
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#completeExceptionally-java.lang.Throwable-
Since Java9, there's also CompletableFuture.failedFuture(Throwable ex)
construct, if you want to return an already failed future.
https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/CompletableFuture.html#failedFuture-java.lang.Throwable-
来源:https://stackoverflow.com/questions/54757857/how-to-fail-a-java-util-concurrent-future