1

I need an advice. There is an MVC action, which interacts with Database through a chain of invocations : Controller->Service->Repository->DbContext. If something goes wrong on repository (entity framework throws exception) I need to catch it in repository, log and pass back to controller action (user have to know that desired action has not been performed). What is the best way to do this :

  1. Catching and rethrowing exceptions this exception in each upper player
  2. Catching and Passing bool status (ok/error) from lower layer
  3. Something else u may offer

Thanks.

Aleksandr
  • 19
  • 2

1 Answers1

0

What is most important is not losing the stack trace, often the best plan is to let the exception bubble up to the outermost try / catch, to do that make sure you just throw rather than throw ex (in the code below). throw ex is like throwing a new exception from that point in the code and may lose vital error info. The most important thing is that when someone comes to fix whatever problem occurred in the repository they have all the error details. It is usually better not to catch at all than to hide the real error.

You could catch in the repository and pass back a success / fail bool to the UI layer. If you do that be sure to log the whole stack trace and all inner execptions, consider calling the repository from a single point in your code where you are catching and logging all your exceptions, disparate logging with slightly different error handling all over the place can lead to lost error details.

Your try / catch in the repository could look like this:

try
{
    // code which may cause an exception
}
catch (Exception ex)
{
    // You can log here
    throw;
}

This has been discussed a lot on various threads SO, you should read Throwing Exceptions best practices.

Community
  • 1
  • 1
jonnarosey
  • 520
  • 1
  • 8
  • 19