cweston
cweston

Reputation: 11647

ASP.Net Exceptions - Catch in Page or handle in Global.asax (Application_Error)

Looking for best practice focused answers here with explanations.

Should the presentation layer of an ASP.Net app catch and handle exceptions thrown from the business layer, or should these be allowed to bubble out, where they can all be logged and handled uniformly in the Global.ascx's Application_Error handler?

ie..

    protected void Application_Error(object sender, EventArgs e)
    {
        logExceptionDetails(Server.GetLastError());
        HttpContext.Current.Server.Transfer("~/Error.aspx");;
    }

Thanks

Upvotes: 1

Views: 8158

Answers (2)

Greg
Greg

Reputation: 16690

My approach to Exceptions is to let them happen and log them with Elmah, and use the built-in Custom Error Page mechanism to notify my user that something went wrong.

All of that can be done with zero code (configured in web.config).

Upvotes: 5

Shiv Kumar
Shiv Kumar

Reputation: 9799

Well, if you need to truely "handle" the exception, then you'll need try-catch blocks in your code where the exceptions might happen.

The method you choose depends on how often you expect the event to occur. If the event is truly exceptional and is an error (such as an unexpected end-of-file), using exception handling is better because less code is executed in the normal case. If the event happens routinely, using the programmatic method to check for errors is better.

However, if you're looking at logging exceptions that have been "uncaught", then you should use Global's Error event like you've shown.This is the best practice. In fact if you implement this as an HttpModule then your Exception handling is non-intrusive and can plugged into other applications or removed by simply altering the web.config file.

Take a look at this article on 4GuysFromRolla

https://web.archive.org/web/20211020134127/https://www.4guysfromrolla.com/articles/081209-1.aspx

Upvotes: 0

Related Questions