Sunday, 29 April 2012

Custom Error handling in asp.net


Custom Error Handling in ASP.NET
Objective: To learn about Error handling mechanism in ASP.NET.
Background: .NET Common Language Runtime provides unified exception architecture.
ASP.NET also provides declarative application custom error handling. It automatically redirects
users to error page when unhandled exceptions occur and prevent ugly error messages from
being sent and displayed to users.
Problem Description: Demonstrate Error handling in ASP.NET.
Step 1: Create a new Web Application,
Step 2: Add three forms to this web application:
(1) HomePage.aspx
(2) GeneralError.aspx
(3) PageNotFound.aspx
Step 3: In HomePage.aspx add a button and set following properties:
ID: btnLogin
Text: Login Page
For the button’s click event, write the following code:
Response.Redirect(“LoginPage.aspx”);
Step 4: In the GeneralError.aspx page, add a label with Text property: General Error Occurred
Step 5: In PageNotFound.aspx, add a label and set Text property to: “You have entered wrong
page. Such page is not found. Try again and check url”
Step 6: In web.config file, make the following changes:


<CustomErrors mode="RemoteOnly" defaultRedirect="GeneralError.aspx">

<error status code="404" Redirect="Pagenotfound.aspx"/></CustomErrors>
Mode attribute is either set to On or RemoteOnly
• On : Custom Error pages will be displayed in client and well as server where application
is running
RemoteOnly : Custom Error pages will be displayed only at client location
Error tag specifies the error status number and page to be redirected when such error occurs.
To see the error status numbers in IIS -> right click on Default Web Site-> Properties-> choose
Custom Errors
Step 7: View the HomePage.aspx in the browser. Click on the button and observe the output.
You will be redirected to the PageNotFound.aspx as Login.aspx page does not exist in your
application.

No comments:

Post a Comment