Customize errors which are not captured by customErrors in ASP.NET 2.0
Yesterday, I came up with an interesting issue where a customer wanted to customize a 500 error message ("Internal Server Error"). Interestingly, customErrors DID NOT seem to work for StatusCode 500! We just wanted to verify if it works for 404, and it did...
<customErrors defaultRedirect="~/ErrorPage.aspx" mode="On">
<error statusCode="500" redirect="~/ErrorPage.aspx" />
<error statusCode="404" redirect="~/ErrorPage.aspx" />
</customErrors>
Ideally, this should have worked... but may be it didn't because some errors are not customizable... https://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/80cb8d8d-8fd8-4af5-bb3b-4d11fff3ab9c.mspx?mfr=true
Let us reproduce the error in just a few steps and then we will fix it by creating an HttpModule to handle our scenario.
1. Create a new ASP.NET web service using VB.NET (or C#)
2. Set Service.asmx as start page.
3. Browse to https://localhost/CustomError/Service.asmx?WSDL => This should work
4. Now, browse to https://localhost/CustomError/Service.asmx?WSDL=12 => This should fail with an error code 500 and description "Internal Server Error"
So, now since we are able to repro this error pretty easily, we will start the next step of fixing this and ensure that whenever this happens, we are redirected appropriately to the ErrorPage.aspx.
1. Start by creating a custom page called ErrorPage.aspx under your project folder directly.
2. Under the App_Code folder create a VB class file called ErrorModule.vb and paste the following code...
Imports Microsoft.VisualBasic
Public Class ErrorModule
Implements IHttpModule
Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
'Hmmm... let it be!
End Sub
Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
AddHandler context.EndRequest, AddressOf ErrorRedirector
End Sub
Public Sub ErrorRedirector(ByVal sender As Object, ByVal e As EventArgs)
Dim myApp As HttpApplication
Dim myContext As HttpContext
Try
myApp = CType(sender, HttpApplication)
myContext = myApp.Context
If myContext.Response.StatusCode.ToString = 500 Then
myContext.Response.Redirect("ErrorPage.aspx")
End If
Catch ex As Exception
'I don't wanna catch it
Finally
myApp = Nothing
myContext = Nothing
End Try
End Sub
End Class
3. In your web.config file paste the following code...
<httpModules>
<add name="MyErrorModule" type="ErrorModule"/>
</httpModules>
4. Compile your project
Now, if you open your browser and browse to https://localhost/CustomError/Service.asmx?WSDL=12, even though you get a 500 error from IIS, you should be redirected to https://localhost/CustomError/ErrorPage.aspx
Yes, it is that simple :o)
Cheers,
Rahul