Saga and AggregateNotFoundException

Hi there,

I am currently developing a simple Saga, and I am struggling with its design.

My Saga is pretty simple: it reacts to an event coming from the Aggregate X, and it sends a command to the Aggregate Y.
It may happen that the Aggregate Y doesn’t exist.
In that case, the Saga should do compensation actions.

This is how the code looks like:

@SagaEventHandler(associationProperty = "a")
fun handle(event: EventFromX) {
    try {
            CommandToY(event.d, event.c, event.e)
    } catch (e: CommandExecutionException) {
            CommandToX(event.a, event.b)

Currently, I catch any CommandExecutionException and pretend that it will always be an AggregateNotFoundException.
How can I check that the exception is an AggregateNotFoundException?

From the documentation, I understand that I need an Interceptor which reacts to every AggregateNotFoundException.
The Interceptor would throw a CommandExecutionException with details of the missing Aggregate.
In this way, I can check the presence of those details inside the Saga exception handling.
If this is the only way to handle the problem, how can I code such an Interceptor?


Maybe something like this?

 class AggregateNotFoundHandler : MessageHandlerInterceptor<CommandMessage<*>> {

    override fun handle(unitOfWork: UnitOfWork<out CommandMessage<*>>?, interceptorChain: InterceptorChain?): Any? {
        try {
            return interceptorChain?.proceed()
        } catch (e: AggregateNotFoundException) {
            throw CommandExecutionException("Aggregate not found", e, e)

Here the assumption is that AggregateNotFoundException will be available on the classpath of the process that is interested in the command handling result. That’s the reason it’s provided as a cause and details to CommandExecutionException, you may need to alter the rethrow logic.

Kind regards,