From 44f0144e629dfe87843fed1692810b65c6dd84fb Mon Sep 17 00:00:00 2001 From: rafal <63915083+rchomczyk@users.noreply.github.com> Date: Thu, 14 Nov 2024 18:20:18 +0100 Subject: [PATCH] Add support for handling async event results --- .../dew/result/ResultHandlerService.java | 20 +++++++++++++++++++ .../dew/result/ResultHandlingException.java | 4 ++++ 2 files changed, 24 insertions(+) diff --git a/dew-common/src/dev/shiza/dew/result/ResultHandlerService.java b/dew-common/src/dev/shiza/dew/result/ResultHandlerService.java index 8555a96..57b4f0c 100644 --- a/dew-common/src/dev/shiza/dew/result/ResultHandlerService.java +++ b/dew-common/src/dev/shiza/dew/result/ResultHandlerService.java @@ -3,6 +3,7 @@ import dev.shiza.dew.event.Event; import java.util.Map; import java.util.Map.Entry; +import java.util.concurrent.CompletableFuture; final class ResultHandlerService implements ResultHandlerFacade { @@ -24,6 +25,12 @@ public void process(final E event, final T value) { return; } + final Class resultType = value.getClass(); + if (resultType == CompletableFuture.class) { + processPromise((CompletableFuture) value, event); + return; + } + final ResultHandler resultHandler = getResultHandler(value.getClass()); if (resultHandler == null) { throw new ResultHandlingException( @@ -34,6 +41,19 @@ public void process(final E event, final T value) { ((ResultHandler) resultHandler).handle(event, value); } + private void processPromise( + final CompletableFuture resultFuture, final E event) { + resultFuture + .whenComplete((result, cause) -> process(event, result)) + .exceptionally( + cause -> { + throw new ResultHandlingException( + "Could not handle result of type %s, because of an exception." + .formatted(cause.getClass().getName()), + cause); + }); + } + private ResultHandler getResultHandler(final Class clazz) { final ResultHandler resultHandler = handlers.get(clazz); if (resultHandler != null) { diff --git a/dew-common/src/dev/shiza/dew/result/ResultHandlingException.java b/dew-common/src/dev/shiza/dew/result/ResultHandlingException.java index 33af4b2..4a8681a 100644 --- a/dew-common/src/dev/shiza/dew/result/ResultHandlingException.java +++ b/dew-common/src/dev/shiza/dew/result/ResultHandlingException.java @@ -5,4 +5,8 @@ public final class ResultHandlingException extends IllegalStateException { public ResultHandlingException(final String message) { super(message); } + + public ResultHandlingException(final String message, final Throwable cause) { + super(message, cause); + } }