Setting custom errors in

If you want more control over what is rendered when there’s a problem with your website, then you will need to set custom errors for any problems you foresee. Two common examples of this are “Page not found aka 404 error” and “Internal server error aka 500 errror”. The 404 err0r happens when a page that doesn’t exist is being requested while the 500 error happens when an error has not been properly trapped in your web application logic.

If you do not set custom error pages, default error pages for those errors will be displayed. There are not very nice looking albeit they convey the message to the more technical person and not the average user. So with custom error pages, you can have your own design which can be in line with your current theme or have something more sophisticated to show to the user and tell the latter what the problem is in very simple terms. However setting these custom error pages can be a problem if you do not understand how they are called.

There are 2 ways to achieve this. The first one relies on you trapping the error in your code and calling your error page. If for example, someone calls a page with an invalid PostId (a post id which does not exist in your database), you can fire off your own custom 404 page. Just remember that you need to do the following before setting the http response code to 404:

Response.TrySkipIisCustomErrors = true;

The second way to have custom error pages in is to set them in the web.config file. There’s a section under system.web for customErrors and here’s how you can use it:

<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/PageError.aspx">
 <error statusCode="404" redirect="~/PageNotFound.aspx"/>
 <error statusCode="500" redirect="~/PageError.aspx"/>

It is important to have a defaultRedirect set, otherwise IIS default error page will be shown for other statusCode that you have not defined.

You will also need to edit your web.config file and add the following to the system.webserver section:

<httpErrors errorMode="Custom">
 <remove statusCode="500" subStatusCode="-1"/>
 <error statusCode="500" path="/PageError.aspx" responseMode="ExecuteURL"/>
 <remove statusCode="404" subStatusCode="-1"/>
 <error statusCode="404" path="/PageNotFound.aspx" responseMode="ExecuteURL"/>

customErrors vs httpErrors – What’ the difference?

For all requests which are served by, customErrors will be called. Any requests which are handled by IIS will be transferred to httpErrors. You can try it for yourself. If you have a folder which does not have a default document (eg default.aspx), then there will be an error. If you don’t have your httpErrors section defined, you won’t see your custom error page but the default IIS error page.

Remember to have the line Response.TrySkipIisCustomErrors = true in your error pages, otherwise IIS default documents might kick in.

Note that I’ve tested this on IIS7.5 and .net framework 4.0.

comments powered by Disqus