Custom Error Handling Using ASP.NET

Sometimes in your application, you may want to show some decent error messages other than red error messages and some message when page is not found or server is busy. We will see custom error message handling mechanism in this article using ASP.NET.

Custom Error Handling:

In ASP.NET, we can customize error message using Web.Config 'CustomError' element.

Syntax is

<customErrors defaultRedirect="URL" mode="On | Off | RemoteOnly">
<
error statusCode="statuscode" redirect="URL"/>
</
customErrors>

Attributes:

defaultRedirect:   

        This specifies default URL to redirect when the error occurs

mode :   

        This specifies whether custom errors are enabled, disabled or enabled only for remote client. 

  1. On - Specifies custom error is enabled.
  2. Off - Specifies custom error is disabled.
  3. RemoteOnly - This is the default. Specifies custom error is enabled for remote client. Means custom error message will be only shown to remote users and generic error message will be to local host.

Error tag:  

  1. statusCode - Specifies HTTP status code that will result in the redirection to the error page.
  2. redirect - Redirect to URL when error occurs

This error tag can be many. We can specify many error codes and custom redirect URL.

We will see one simple example which opens custom error page when page not found error occurs(404 error) and some exception occurs.

In web.config:

Specify like this...

<configuration>
<
system. web>
<
customErrors defaultRedirect="GeneralError.htm" mode="On">
<
error statusCode="404" redirect="pagenotfound.htm"/>
</
customErrors>
</
system. web>
</
configuration>

Create pagenotfound.htm and place it in the same path where project file exists.

<html>
<
head><title>Test Custom Error Page</title></head>
<
body>
<
p align="center">Page you are looking for is not found.</p>
</
body>
</
html>

Create GenericError.htm

<html>
<
head><title>Test Custom Error Page</title></head>
<
body>
<
p align="center">Unhandled Error Occurred.Please Try Later</p>
</
body>
</
html>

Test.aspx :

In Page_Load add these line

throw new IndexOutOfRangeException();

For testing , type some file name which doesn't exist in your virtual directory for 404 error...For example..if you have Test as your virtual directory name and TestError.aspx doesn't exist in your directory.

Type http://localhost/Test/TestError.aspx

You will get our custom error page 'pagenotfound.htm' instead of usual IIS 404.htm page.

Type http://localhost/Test/Test.aspx . This will open GenericError.htm. Whenever some exception occurs this page will be opened.

This way you can customize your error message.

Hope this article would have helped you all. Good Day...