Reputation: 58454
After the command operation is handled by the handler, I raise the domain events. In some cases, it's tolerable for an event handler to fail. I can say that this is the case for most of them and I want all of the event handlers to be failure tolerable.
Should my operation fail if an event handler fails or should the event handlers be fire and forget?
As an example, assume that this is the place I raise the events and as you can see, potential exceptions coming from eventHandler.Execute
are not handled.
public void Publish<TEvent>(TEvent @event) where TEvent : IDomainEvent
{
IEnumerable<IEventHandler<TEvent>> handlers = _lifetimeScope.GetService<IEnumerable<IEventHandler<TEvent>>>();
var eventHandlers = handlers as IEventHandler<TEvent>[] ?? handlers.ToArray();
if (eventHandlers.Any())
{
foreach (IEventHandler<TEvent> eventHandler in eventHandlers)
{
eventHandler.Execute(@event);
}
}
else
{
throw new InvalidOperationException("No handler registered");
}
}
However, my desire is to have something like below:
public void Publish<TEvent>(TEvent @event) where TEvent : IDomainEvent
{
IEnumerable<IEventHandler<TEvent>> handlers = _lifetimeScope.GetService<IEnumerable<IEventHandler<TEvent>>>();
var eventHandlers = handlers as IEventHandler<TEvent>[] ?? handlers.ToArray();
if (eventHandlers.Any())
{
foreach (IEventHandler<TEvent> eventHandler in eventHandlers)
{
try
{
eventHandler.Execute(@event);
}
catch (Exception ex)
{
// log the expection
// swallow it
}
}
}
else
{
throw new InvalidOperationException("No handler registered");
}
}
Upvotes: 0
Views: 850
Reputation: 233150
I usually put events on a persisted pub/sub system, and then return from the Command Handler.
In that way, individual event handlers can fail without impacting the main system, or each other.
Upvotes: 4