1

I'm having this thought on my mind for quite some time and i still can not find any answer. My DbContext is handled by an UnitOfWork class. So i have one place where savechanges occur and i am catching all of those nasty exceptions and handling them in one place.

But, as it is widely known, the DbContext can sometimes throw other types of exceptions in another places besides in the SaveChanges() method. For example when materializing the entities. But this can happen in many places and it is sometimes overhead to write try catch blocks on every FirstOrDefault() or ToList() call and catching and re throwing exceptions. Sometimes this exceptions can be of SQL type meaning a connection cannot be open, EntityCommandExecutionException or others.

So i was wondering is there any event that DbContext object fires when an exception occurs, so i can subscribe to that event and handle some logic in these scenarios. :)

mravko
  • 49
  • 1
  • 6

1 Answers1

2

No, there isn't. And never will be, for (at least) three reasons:

  1. Exceptions may be thrown intentionally, but they can also just occur somewhere in EF's source code and bubble up. In the former case they could fire an event, in the latter case not. So you'll never be safe.

  2. How should the event be fired? There are several ways to throw an event. One of them is just re-throw in a catch block. Firing an event in a catch block sounds like very bad practice. Catch blocks should contain safe, stable code. If an exception occurs in a catch block things go from bad to worse. It would give me a very bad feeling if anyone could hook up any kind of code in my catch blocks.

  3. When should the event be fired? Some exceptions may be thrown and handled within the EF assembly. You probably never even want to know they occurred. But in another scenario the same exception may bubble up.

Community
  • 1
  • 1
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
  • First of all, thank you for your answer. In that case, can you please provide some links or keywords of how to handle exceptions like timeout, cannot open connection (others beside DbUpdate and Concurrency) in a more centralized way. – mravko Apr 07 '13 at 20:11
  • 1
    There are some ideas [here](http://stackoverflow.com/questions/3699799/is-there-a-centralised-error-handling-process-in-c-sharp) but the bottom line is: you have to handle them where you don't want them to bubble up, so you'll always have `try-catch` blocks. – Gert Arnold Apr 07 '13 at 20:20