Return 404 NOT FOUND when CommandHandler fails

Hello,
I’m trying to understand which way is the best or if there’s something i can’t make work ok.

Supposing I have this Spring Web Controller POST method:

`

@POST
@Path("/update")

public Response handle(UpdateJobCategoryPayload payload) {

FutureCallback<UpdateJobCategory, Void> cb = new FutureCallback<>();

commandBus.dispatch(asCommandMessage(payload.asCommand()), cb);

if (cb.isDone()) {

try {

cb.get();

} catch (ExecutionException e) {

return Response.status(Status.NOT_FOUND).build();

}

return Response.ok().build();

}

return Response.serverError().build();

}

`

When CommandHandler fails, no exception has been thrown. So I tried to handle it async and inspecting class hierarchy I found this FutureCallback<C, R>. Changing the domain code and now I’m able to catch an ExecutionException I can inspect to get if the AggregateKey is not found.

The documentation lacks of some information to understand if I wrote my code ok! Can you please provide your ideas?

This code smells very very much.

TIA!

Hi Samuele,

assuming you’re using Spring 4, just “embrace” the async features, instead of fighting against them. By the way, running your code async would probably always result in a Response.serverError(), as “isDone()” will return false when a Future hasn’t been resolved yet.

Here’s how I would write it:

public CompletableFuture<Response> handle(UpdateJobCategoryPayload payload) {

    FutureCallback<UpdateJobCategory, Void> cb = new FutureCallback<>();

    commandBus.dispatch(asCommandMessage(payload.asCommand()), cb);
    return cb.thenApply(r -> Response.ok().build())
            .exceptionally(e -> Response.status(Status.NOT_FOUND).build());
}

Cheers,

Allard

Hi Samuele,

The NoOpCallback wont give you anything on execution.
So if you’d want your command dispatches to be fire and forget, using the NoOpCallback could help, but I’m guessing that’s not what you’re after.

If I follow correctly, you do not care about the result of the dispatching of the command, right?
In that case using the Void result type on the FutureCallback is fine, since you wont care about the result, but still wait to see whether the result is an exception.
The exception is than giving to you as e in the .exceptionally() function call Allard described.

Cheers, Steven