Exception Handling on Commands

Hello guys,

I’m using Axon Framework with Spring, but I came to a problem while implementing a specific use case.

I want to, depending on the business logic, apply an Event and then throw an Exception.

Here is a code example:

    public void handler(SomeCommand cmd){

        if (condition1 == condition2) {
            apply(someEvent()); // I want to apply the event
            throw new SpecificRuntimeException("exception Error"); // then throw an exception

The problem is, when I throw an error, the apply event doesn’t happen.

Why am I using this approach?
Because the SpecificRuntimeException is handled by the ControllerAdvice annotation from Spring, this way, depending on the exception I’m throwing on the command I can specify a different status code for each of them.

A possible solution that I found is, instead of applying the Event on the aggregator command I apply it outside of the aggregator on the ControllerAdvice, here is a piece of code:

long seqNumber = eventStore.lastSequenceNumberFor(instanceKey()).get() + 1L;
 eventGateway.publish(new GenericDomainEventMessage<>("someType", instanceKey, seqNumber, new someEvent(ex.getErrorMessages().toString())));

Why am I not convinced with this approach?

  • Maybe the eventStore.lastSequenceNumberFor can have thread problems? Also the “+1l”?
  • Sending an event outside of the aggregator can be an anti-pattern or “something ugly” to do.

Thank you!

Hi Nelson,

I don’t understand why you want to persist the event in case of failures. Could you please explain that bit? When there is any error bubbling up, we make sure no events are persisted, which most times is exactly what you want. Going around this mechanism is indeed an anti-pattern.

Hello Gerald,

First of all, thank you for the reply.

Maybe I’m going in the wrong direction, and I know that what I’m trying to do is not right.
The event I’m applying for is responsible for clearing some fields in the aggregator, and also the error message is stored in the database.
Maybe the error scenarios shouldn’t be stored in the event database?

It all depends. If the errors are valuable, and should change state, you could have something like an UnauthorizedAccessEvent. In which case, the commands should likely finish successfully. You could optionally return something like a String with an error code from the command handler, so that the application sending the command can know there was an error.

That makes sense, instead of throwing an exception I’ll just apply the event and then return something to the controller. Then the controller can handle the response based on the returned thing from the command.

1 Like