Friday, 17 August 2012

.Net Beginners : Handling errors using Custom Errors configuration settings in web.config

When error occurred in .Net application Asp.Net page display it's default error page with the source code and line number of the error. This approach is not good it has some issues like.
  1. If source code and the error messages are displayed to a hacker it could damage application.
  2. And this message do not able to understand normal users.
There is a solution for this in ASP.Net. You can make settings in Web.Config file using "<customErrors>" section.

Syntax :
<customErrors defaultRedirect="[url]" mode="[on/off/remote]">
<error statusCode="[statuscode]" redirect="[url]" />
</customErrors>
  • defaultRedirect : Specifies URL to which page should be redirected if an error occurs. This setting is optional.
  • mode : Specifies the status of the custom errors is enabled, disabled, or shown only to remote machines. The values are On, Off, and RemoteOnly. "On" means that the custom errors are enabled. "Off" means that the custom errors are disabled. "RemoteOnly" means that the custom errors are shown only to remote clients. 
  • customErrors : The "<customErrors>" section has multiple <error> sub-elements that are used to define custom errors. Each <error> sub-element can has a statusCode attribute and a URL.

Here is example for this.
In this example we forcefully raise error from code and after error raise page is redirected to our custom "ErrorPage.aspx". In this example we raise error using numeric value divide by zero.
Here you have to add one aspx page into your .net application.
We specify settings in "web.config" file.
You have to put  "<customErrors>" section in  "<system.web>" section.

Web.Config :
<customErrors defaultRedirect="ErrorPage.aspx" mode="On">
</customErrors>

C# Examples :
        int a=1;
        int b = 0;
        a = a / b;

VB.net Examples :
        Dim a As Integer = 1
        Dim b As Integer = 0
        a = a / b
Output :
(To view original image , click on image)

If you do not handle error, error message display on screen. You can see in below screen shot.

.

 (To view original image , click on image)

This is very useful articles for Beginning .Net .

This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.




No comments:

Post a Comment