Currently, we are doing error handling via 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 into a database, displays an informative 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
is necessary, because otherwise the default ASP.NET error handling kicks in and the user is shown -- depending on the current state of <customErrors>
-- either the "yellow screen of death" or an information message about how <customErrors>
can be turned off.
The drawback of using ClearError
is that I can no longer use <customErrors>
to override the error handling behaviour -- something which brought quite a bit of trouble during the recent ASP.NET vulnerability, where the recommended workaround was done using <customErrors>
.
I know that I could use only customErrors
and show the information for the user in the page referenced by the defaultRedirect
attribute, but that would require me to add this error page to every single web project (rather than having everything nicely centralized in one library function).
Is it possible to do regular error handling in Application_Error, but still allow it to be overridden by <customErrors>
? Is that even best practice or am I doing something fundamentally wrong?
PS: Many of our applications are hosted on our customer's servers (instead of our own), so "put all information in the application log and show nothing to the user" is not really an option.
Solution: Replace httpApp.Server.ClearError()
with
If Not HttpContext.Current.IsCustomErrorEnabled Then httpApp.Server.ClearError()