I needed to handle async events safely without the risk of "implicit parallelism", and so implemented the "deferral" mechanism advised by @StephenCleary, using his Nito.AsyncEx / Nito.AsyncEx.Oop library and great tutorial on async events.
It works well. So my event subscriber looks like this:
dbContext.SavingChanges += async (sender, e) => {
using (e.GetDeferral()) {
Audit();
await Validate(); // this could throw
}
};
However, suppose that Validate()
throws an exception. I need it to "bubble up" to the event's producer. In other words, since this is a "command event", which updates the event producer when it's done, I'd like the exception to also reach there. But it doesn't of course.
Is there a way to do that?
(Background: just before the db context saves, it raises events for handlers to do extra work, e.g. auditing, validation. If validation fails, I want the context to catch the exception so it can abort the save.)