Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I catch all my exceptions in the global.asax?

If I am just logging exception details in my web app, do I really need to put in exception handling logic for each tier? Why not just let them all bubble up the stack trace to the global.asax and log them there?

like image 897
mcass20 Avatar asked Dec 19 '25 04:12

mcass20


1 Answers

I would suggest against using any exception handling logic in any layer of your application unless:

  • The exception is not a fatal one, meaning that there is some action you can take to recover, or
  • The application should continue functioning and the exception should be "ignored." An example: when checking out at an online retailer you are sent a receipt via email. If that fails - but the other order processing stuff succeeds - the user should not be shown an error page. Here, we want the workflow to continue even though there is an exception. Most exceptions do not fall into this category.

Of course, exceptions - whether they are fatal or not or should be "ignored" or not - need to be logged and developers notified. This is best handled through an event handler for the Application.Error event. Yes, this can be done in Global.asax, but I think it's cleaner to use an HTTP Module-based approach, either Health Monitoring or ELMAH.

I've written an article on this topic that I'd like to recommend to you - Exception Handling Advice for ASP.NET Web Applications. Here is the article in summary:

My advice for handling exceptions in an ASP.NET application can be boiled down to the following guidelines:

(a) Create and use a meaningful custom error page.

(b) In general, do not catch exceptions. Let them bubble up to the ASP.NET runtime. Some cases where catching an exception makes sense include:

  • When there is a plausible way to recover from the exception by performing some alternative logic,

  • When a peripheral part of the application's workflow throws and exception and that exception should not derail the entire application, and

  • When you need to include additional information with the exception by throwing a new exception that has the original exception as its inner exception.

(c) Log all exceptions to some persistent store and use email (or some other medium) to notify developers when an exception occurs in production. Consider using ELMAH or ASP.NET's built-in Health Monitoring system to facilitate this process.

like image 56
Scott Mitchell Avatar answered Dec 21 '25 01:12

Scott Mitchell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!