diff --git a/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgPoolTestBase.java b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgPoolTestBase.java index 0b51462fb..a6c91475e 100644 --- a/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgPoolTestBase.java +++ b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgPoolTestBase.java @@ -30,6 +30,7 @@ import org.junit.Before; import org.junit.Test; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; @@ -256,4 +257,24 @@ public void testWithConnection(TestContext ctx) { } } } + + @Test + public void testWithConnectionFunctionThrows(TestContext ctx) { + Pool pool = createPool(options, new PoolOptions() + .setMaxSize(1) + .setConnectionTimeout(2) + .setConnectionTimeoutUnit(TimeUnit.SECONDS)); + RuntimeException failure = new RuntimeException("The function fails"); + pool + .withConnection(conn -> { + throw failure; + }) + .onComplete(ctx.asyncAssertFailure(err -> { + ctx.assertEquals(failure, err); + // The only connection of the pool must have been returned + pool + .withConnection(conn -> conn.query("SELECT 1").execute()) + .onComplete(ctx.asyncAssertSuccess()); + })); + } } diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/Pool.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/Pool.java index 9adb88b8e..bddefb664 100644 --- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/Pool.java +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/Pool.java @@ -185,7 +185,15 @@ static Pool pool(Vertx vertx, SqlConnectOptions database, PoolOptions options) { * @return a future notified with the result */ default Future<@Nullable T> withConnection(Function> function) { - return getConnection().flatMap(conn -> function.apply(conn).onComplete(ar -> conn.close())); + return getConnection().flatMap(conn -> { + Future<@Nullable T> result; + try { + result = function.apply(conn); + } catch (Throwable t) { + result = Future.failedFuture(t); + } + return result.onComplete(ar -> conn.close()); + }); } /**