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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With