Search This Blog

Saturday, January 1, 2011

Custom Error Pages in ASP.NET

The default error page is a catchall for any type of error that may occur for resources managed by ASP.NET, so it has to be relatively generic. In some cases we might need to create custom error pages as the generic pages will not tell the whole story. For example, if a user attempts to access a nonexistent resource managed by ASP.NET, then the user receives a 404
error. If, however, you have only specified a default error page, then ASP.NET displays that error page without ever mentioning that the resource was not found. This makes it appear as though the resource exists and is having errors.

To avoid this we could create a 404 error page that informs the user that the page they are trying to access does not exist so they know they entered the wrong URL. We could even go as far as displaying a site map, links, or a search box to allow the user to more easily locate their desired content. Defining custom error pages requires adding an <error> inner element to the
<customErrors> element in Web.config. The following lines show an example that defines a custom error page for the 404 error.

<customErrors mode="On" defaultRedirect="~/ErrorPages/GenericError.html">
<error statusCode="404" redirect="~/ErrorPages/Error404.html"/>

The statusCode parameter of the <error> element defines the server status code for which the error page should be returned. The redirect parameter defines the actual error page location. In this example, if a 404 error occurs, ASP.NET redirects the user to the Error404.html page. Because the 404 error is the only custom error defined, any other error will cause the user to be redirected to the GenericError.html page.

No comments:

Post a Comment