Web developers wiki ASP.NET Sitecore Sharepoint Kentico by Evident Interactive

ASP.NET: 500 error page sometimes doesn't work

Modified: 2011/06/10 09:57 by vanthoog - Categorized as: ASP.NET
In an ASP.NET application you can set up a custom error page for 500 errors. You can do this by putting the following definition in the web.config:

	<customErrors mode="On" redirectMode="ResponseRewrite">
		<error statusCode="500" redirect="~/Pages/GeneralError.aspx"/>

In this case, when a 500 error occurs, the page "/Pages/GeneralError.aspx" will be displayed. If you do not change anything in the (empty) code-behind of "/Pages/GeneralError.aspx" the http-status 200 is returned (by default). Usually you do want to inform the browser that something went wrong, so it is good practice to return the http-status 500 in this case. This can easily be achieved by putting the following line of code in the OnLoad of the error page:

	Response.StatusCode = 500;

It is also possible to set the StatusDescription of the Response object. So you might put the text of the last exception in the StatusDescription:

	Exception exc = Server.GetLastError();
	Response.StatusDescription = exc.Message;

When you do this the strange situation may occur that your error page may sometimes not work and the default ASP.NET error page is returned. The reason for this is that the property StatusDescription may not contain a text longer than 512 characters! If it is set to a text longer than 512 characters, a System.ArgumentOutOfRangeException will be thrown. If the code does not catch this exception, the default ASP.NET error page will be returned.

The solution to this problem is simple. Make sure the text is smaller than 512 characters or put a try-catch around the code for setting the property StatusDescription.

 © Evident Interactive BV