Global try-catch in presentation layer

design-patternserror handling

I have a 3-layered app structured as follows.

  • Presentation Layer (ASP.NET MVC project)
  • Business Logic Layer (Services for controllers in PL)
  • Data Access Layer (Repositories)

Each Controller in PL interacts with its service in BLL, which in turn has access to Repositories in DAL.

Is it a good practice to do a "global" try-catch in the PL? That way if exception is thrown in DAL, for example, I can display the error message to the user. Or is there a better way to do this?

Best Answer

Your presentation layer should have a fault barrier. All decent frameworks will let you configure it once only, for unexpected exceptions. So try-catch does not pollute every controller method.

When you want to show the error message to the user, then catch the exception in the specific controller. However, this is only useful if the user can do something about it, so don't catch all exceptions in the controller catch block - let most of them fall through to the fault barrier.

See this article http://www.oracle.com/technetwork/articles/entarch/effective-exceptions2-097044.html. It's about Java, so the checked/unchecked distinction doesn't apply, but you should still follow the pattern of faults vs contingencies