Best practices for handling exceptions during CommandGateway send() or sendAndWait()

There are some of snip codes that try-catch send() or sendAndWait() with RuntimeException.
Is there kind of best practices for handling exceptions instead of catching RuntimeException ?

Plus, When I read CommandGateway class javadoc, I can see the comment as bellow :

  • sendAndWait() will be blocked “until the Thread is interrupted”.

when is exactly the Thread interrupted? or any use-cases that make the Thread be interrupted?

Hi Juya,

What I typically like to do is use the send() function, as this returns a CompletableFuture to you.
The CompletableFuture has an exceptionally() function on it, which is called if the operation fails with whatever exception being thrown.
That way you can easily make some compensating action if necessary.
Next to that, I think is based on taste, not so much on how to use Axon.

A lot of users tend to have a REST endpoint which in turn publishes a command on the CommandGateway.
With for example spring, there are plenty of option to do something smart depending on the exception being thrown.

Again though, that’s outside the scope of Axon Framework I’d think.

You could also use the CommandBus i.o. the CommandGateway. This will give you a CommandResultMessage upon finishing the dispatch call.
The CommandResultMessage in turn contains a success or a failure, so yet again another technique to deal with potential exceptions being thrown by your Command Handlers.

Reading this back however, I think it is hard to give you one right answer, except for ‘it depends’.
Hope this sheds some light on what options you have. Pick whichever you fancy the most. :slight_smile:

On the ‘until the Thread is interrupted’ part, the framework is not deliberately ending any of your threads unless you tell it to.
So you must seek the conclusion in ‘when does this happen’ more so in when your application halts/stops/breaks down/etc.

Hope this helps you out Juya!

Cheers,
Steven