Centralized ASP.NET error handling: <customErrors> and Application_Error. Can both options be used?
We are currently doing error handling with Application_Error in global.asax.vb :
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) OurLibrary.HandleError(Me) End Sub HandleError then logs the error in the database, displays an informational message to the user and returns the correct status code (404 or 500) depending on the type of exception that occurred:
Public Shared Sub HandleError(httpApp As HttpApplication) ''# do some logging ... ''# show some details about the error and information about how to contact us httpApp.Response.Write(...) httpApp.Response.StatusCode = 404 or 500 httpApp.Server.ClearError() End Sub Server.ClearError necessary, because otherwise ASP.NET error processing starts by default, and the user is displayed - depending on the current state of <customErrors> - either the "yellow screen of death" or an informational message about how <customErrors> can be disabled .
The downside of using ClearError is that I can no longer use <customErrors> to override the error handling behavior - something that brought a lot of problems during the recent ASP.NET vulnerability where the recommended workaround was done using <customErrors> .
I know that I can only use customErrors and display information for the user on the page referenced by the defaultRedirect attribute, but I need to add this error page to every web project (and not everything is beautifully centralized in one library function).
Is it possible to perform regular error handling in Application_Error, but still allow it to be overridden by <customErrors> ? Is this even the best practice or am I doing something fundamentally wrong?
PS: Many of our applications are hosted on our client servers (instead of our own), so "putting all the information in the application log and not showing anything to the user" is actually not an option.
Solution . Replace httpApp.Server.ClearError() with
If Not HttpContext.Current.IsCustomErrorEnabled Then httpApp.Server.ClearError() Personally, most of the time I see people choose an approach similar to what you do. There are a number of benefits to doing things your way.
- Errors are no longer written to the application log in Windows, this helps minimize interference / overhead.
- You have an easy deployment method to add your journal, as you mentioned.
There are a number of workarounds that I noticed in the past, but most common for users, so that their user exit knows about setting CustomErrors. Thus, basically your code will look at the response code that it wants to send, and then take action based on user errors. This is truly the best of both worlds.