ardalis / DomainEventsConsole

A console app showing domain events in action using .NET 5

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Doubt: How to handle errors in domain events

David-Moreira opened this issue · comments

Hello @ardalis

I base some of my projects on your clean architecture, and I've always had this doubt... with domain events.
How do you handle any possible errors or downtime that may happen on this piece of code? Or do you just not define critical bussiness "happenings" as a domain event like you're showing in the example, where it 's just simple UI notifcations?

            var eventsCopy = entity.Events.ToArray();
            entity.Events.Clear();
            foreach (var domainEvent in eventsCopy)
            {
                await _mediator.Publish(domainEvent).ConfigureAwait(false);
            }

Keep up the good work! Thanks!

Closing as no activity / answer...

Hey David. Sorry, missed this originally but your closing/comment caught my attention.

I used to use domain event exceptions for things like validation but more recently I've come around to the idea that raising events should never fail, because essentially the act of raising an event just means saying "this happened" and shouldn't generate a direct response. If a response is needed, then that should be a command not an event and so more recently I've been considering how to use command-based messages rather than domain events for things like validating business rules or invariants.

Now, I'm not sure that answers your question. In the code you list above, if I want to follow my ideals from the previous paragraph, I might wrap the contents of the foreach in a try-catch that logs but otherwise doesn't bubble up any exceptions that occur. I would also make sure my handlers weren't throwing exceptions as a matter of course (any that occur would be truly exceptional, not the result of a guard clause or validation issue).

In terms of what did I do before I changed my outlook on events? I just let them bubble up. The first handler that threw would break the foreach loop and bubble up to the code that had raised the event, eventually being caught somewhere (the global error handler if nothing else). Does that help?