3

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?

2 Answers 2

5

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

2
  • 1
    I wouldn't say you shouldn't catch all exceptions, I agree with you in every other way but regarding the top level requirement to be able to do something about it, I disagree. I think you should catch exceptions only if you can do something about them in lower layers, but in the top layer there's always something you can do about it: Not crash, give an error message, log it, and try to recover back to at least the beginning of the app if no other state is recoverable. The top layer should choose the current state of the whole app, as such it should be responsible for such recovery. Commented May 22, 2014 at 16:46
  • @JimmyHoffa That's what the fault barrier is for. I was saying don't catch all exceptions in each controller
    – artbristol
    Commented May 23, 2014 at 8:09
0

In ASP.Net, you can setup an Error page in your Web Config that can handle the display of any uncaught errors in the method of your choosing. Setting up a global try/catch can cause issues in catching your errors. Your error page should be setup to show your error message and, if you want the user to see the error, display any error you've received.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.