Search code examples
lagom

ctx.commandFailed vs throwing in PersistentEntity


In the Auction Example I have seen both ctx.commandFailed(...) and throw SomeException(...). Is there a good reason to throw instead of using the API and is there a difference between the two?


Solution

  • Persistent entity command handlers and after persist callbacks are wrapped in try/catch blocks, if an exception is caught, it will pass that exception to ctx.commandFailed(...) for you.

    There is a subtle difference between the two to be aware of. If you throw an exception, processing of the command will of course stop immediately. If however you pass an exception to ctx.commandFailed(...), that will send the exception back to the invoker of the command, however it won't stop processing. You could in theory go on to return some directives to persist events - which would be an odd thing to do. In practice what you need to do is return ctx.done after invoking ctx.commandFailed(...).

    In general it's probably simpler and safer to simply throw the exception.