Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global error handling in ASP.NET

Is there anything wrong with catching errors in an ASP.NET application globally (eg: Global.asax)? I have viewed the question Good error handling practice and it doesn't really say too much about this.

My experience has been excluding some very specific circumstances (such as transactions) most of the ASP.NET applications we are writing are along the lines of

void ButtonEventHandler(object sender, EventArgs e) {
    Page.Validate();
    if (Page.IsValid) {
        //Do a database insert or update thru relevant datalayers.
        //If its a transaction then we rollback internally and rethrow
        //the exception.
    }
}

Why not just have a global exception handler? Usually (at this point) the only thing I can do is abort the operation gracefully and tell the user to try again.

like image 540
Maxim Gershkovich Avatar asked Oct 24 '11 12:10

Maxim Gershkovich


People also ask

What is global error handling?

The global error handler is used catch all errors and remove the need for duplicated error handling code throughout the . NET api. It's configured as middleware in the configure HTTP request pipeline section of the Program.

How does ASP.NET handle global exception?

ASP.NET Core Error HandlingAn ExceptionFilterAttribute is used to collect unhandled exceptions. You can register it as a global filter, and it will function as a global exception handler. Another option is to use a custom middleware designed to do nothing but catch unhandled exceptions.

How do I create a global error handler?

Steps for phase 2 implementation: Defining “Global Error Handler Configuration” Step 1: Select the “Global Elements” tab in Anypoint Studio. Step 1b: The “Global Configuration Elements” panel will appear. Step 2: Select the “Create” button from the “Global Configuration Elements” panel.


2 Answers

The global place to handle uncatched Exceptions would be in Global.asax by handling Application_Error. As John pointed out, you should always handle exceptions as close as possible to where they might occur and react appropriately.

like image 172
Icarus Avatar answered Oct 05 '22 19:10

Icarus


I think so. You should catch exceptions that you might expect on a particular operation as close to it as possible, and behave appropriately, but barring that (or perhaps following it after it does some clean-up and rethrows) a global handler that logs the exception and goes to a general 500 response is a good default behaviour.

like image 32
Jon Hanna Avatar answered Oct 05 '22 19:10

Jon Hanna