Exception handling in ASP.NET for multi-tiered apps RRS feed

  • Question

  • Reading through different threads related to Exception Handling best practices in ASP.NET, I am a bit confused about the best strategy to implement for a classical multi-tiered asp.net app.

    My initial idea was to handle exceptions at layer boundaries, log them right at the point of infraction and wrap/replace the exception into layer specific exception types to be handled by callers up the stack. For example, all my public methods in my DAL, BLL and Presenter layer(my application follows MVP) have try catch blocks and catch on the broad Exception type(which is in itself a bad idea but I chose it to ensure that exceptions crossing layer boundaries are cast into the layer specific exception type). Callers up the stack like the the UI can either choose to handle the exception(if it is of type Validation Exception -- needs to be displayed to the user) or let it be handled by the Global Exception Handler(Application_Error handler in the Global.asax) where the error is mailed to the dev/support team and a user friendly custom error page is displayed to the user.

    This seemed to me to be a reasonable design. But on a little bit of research, I found that a best practice guideline says not to catch exceptions unless you can gracefully recover from them and allow some global exception handler to take the necessary steps as per the desired design. So that would mean that all the code below the UI(the top layer of the call stack) should just ignore exceptions and let the exception bubble up to the global handler where it can get logged, mailed and notified appropriately to the user.

    While this is definitely a much more easier approach to implement, I have seen a lot of good apps having custom layer specific exception types which are being thrown when the code crosses a layer boundary. These types are just derived from the Base exception type and are not adding any additional information about the exception. These are being used only for the callers above the stack to decide the correct choice of action -- whether to log/wrap/replace/rethrow the exception.

    So my question is under what circumstances is the Custom Exception types a better choice and when should I resort to a having only a global exception handler to handle all my exceptions?


    Wednesday, March 7, 2012 5:24 AM