I'm wondering if it's preferable to publish events rather than throw exceptions from aggregates. Say, I have a domain where there is a requirement that only students of a certain grade level can enroll for sports. If I call EnrollForSports on a student that does not satisfy the criteria, should the aggregate throw an exception or publish an event, particularly if other aggregates or process managers are interested in the result of the process?
If an event is published, doesn't it mean there would be a need for a corresponding internal event handler to handle the event when we're replaying, even though the event wouldn't change the state of the aggregate?
If an exception is thrown, how will the other parties get notified? Can the command handler catch the exception and then raise an event? Can events be raised from command handlers?
This question can't be generally answered. There is no "best practice", it really depends on many factors.
Nevertheless this topic has just recently been discussed at the DDD/CQRS mailing list. Read it and you will probably find some interesting and helpful points over there.
Oh, and here's a blog post on the topic: Business Errors are Just Ordinary Events
Principally speaking, a command should be either valid and executed, or invalid and not executed. The idea with spawning error events leaves you somewhere in the middle and the feedback to whomever sends the command is ambiguous and delayed. It is also an unnecessary complexity in your domain. If you throw an exception it will come as an immediate feedback to to the client code which sent the command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With