Skip to content

Commit

Permalink
Add support for handling async event results
Browse files Browse the repository at this point in the history
  • Loading branch information
rchomczyk committed Nov 14, 2024
1 parent 6ad56ee commit 44f0144
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
20 changes: 20 additions & 0 deletions dew-common/src/dev/shiza/dew/result/ResultHandlerService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand All @@ -24,6 +25,12 @@ public <E extends Event, T> 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(
Expand All @@ -34,6 +41,19 @@ public <E extends Event, T> void process(final E event, final T value) {
((ResultHandler<E, T>) resultHandler).handle(event, value);
}

private <E extends Event, T> void processPromise(
final CompletableFuture<T> 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit 44f0144

Please sign in to comment.