Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Error events in asp.net - Part 70

Suggested Videos
Part 67 - Asp.net Application state
Part 68 - Asp.net application state real time example
Part 69 - Exception handling in asp.net

Handling exceptions using try/catch blocks is commonly termed as structured exception handling. Asp.net provide 2 error events
Page_Error - This event is raised at the page level, when there is an unhandled exception on the page. The event handler resides on the page.
Application_Error - This event is raised at the application level, when there is an unhandled exception at an application level. The event handler resides in Global.asax file

These error events can be used as a substitute or supplemental to structured exceptional handling.



Create an asp.net web application. Add a webform with name Errors.aspx. Copy and paste the following HTML in Errors.aspx.
<div style="font-family: Arial">
    <table style="border:1px solid black">
        <tr>
            <td style="color:Red">
                <h2>Application Error</h2>
            </td>
        </tr>
        <tr>
            <td>
                <h3>
                    An unkown error has occured. We are aware of it and the IT team is currently working
                    on this issue. Sorry for the inconvinience caused.</h3>
            </td>
        </tr>
        <tr>
            <td>
                <h5>
                    If you need further assistance, please contact our helpdesk at helpdesk@companyhelpdesk.com
                </h5>
            </td>
        </tr>
    </table>
</div>



Add WebForm1.aspx to the project. Drag and drop a gridview control. Copy and paste the following code in Webform1.aspx.cs. 
protected void Page_Load(object sender, EventArgs e)
{
    DataSet ds = new DataSet();
    ds.ReadXml(Server.MapPath("~/Data/Countries.xml"));

    GridView1.DataSource = ds;
    GridView1.DataBind();
}

protected void Page_Error(object sender, EventArgs e)
{
    // Get the exception details and log it in the database or event viewer
    Exception ex = Server.GetLastError();
    // Clear the exception
    Server.ClearError();
    // Redirect user to Error page
    Response.Redirect("Errors.aspx");
}

The code tries to read xml data from Countries.xml file. At the moment, the file is not present and we get a FileNotFound exception. Since this exception is not handled using a try/catch block in the Page_Load event, the eror get to the page level and is handled by Page_Error event handler. In Page_Error event handler
1. We get the exception information using Server.GetLastError() method.
2. Do something with the exception, such as redirect the user to a generic error page, display an error message on the same page which caused the exception, try to correct the problem, or log the exception to a database table or event viewer and notify the development team. We will discuss about logging and notifications in a later video session.
3. We then clear, the exception, so that it is not get propagated to the application level.
4. Finally we redirect the user to a generic error page, Errors.aspx

Please note that 
1. If the exception is not cleared in the Page_Error event, it gets propagated to the application level, and Application_Error event handler gets executed. If we are not clearing the exception at the application level, the application crashes with the "Yellow Screen of Death".
2. If the exception is cleared and redirection to Errors.aspx is not done, then a blank page is displayed.  This is because web form processing is immediately stopped when an exception occurs.

If an exception is not handled at the page level using Page_Error event, it get's to the application level and can be handled using the Application_Error event handler in Global.asax and can be used as a single, centralized location for error handling.

3 comments:

  1. Hi Venkat,
    There is a situation in one of my web application wherein I’ve used the try catch technique for almost all of the methods, functions etc. But during the development phase I wasn’t sure which logging method I was going to use (i.e. database, event viewer, mail) hence I’d just used a label in the catch block to display the error to the user. And now that I’m almost done with the development work, I want to handle the exception in a proper way, for which I thought of using the error events that is mentioned in this video but my problem is the catch block that I’ve used in all of my code which doesn’t allow the error to be propagated to either Page level or Application level error events.
    I know that I’ve messed up big time but is there any technique to handle the exceptions in above mentioned scenario other then adding logic for error logging in each and every catch block?

    Thanks,
    Rohan

    ReplyDelete
    Replies
    1. Hello Rohan,
      I did the same as you have done initially, try catch . I just checked Venkat article and I am thinking to implement Page_Error event. Rohan I have thought that If try catch unable to handle the Exception than only Page_error event will excute and same applies for Application_Error. So we can have Page_error, application_error.
      What do you think on this?????????

      Delete
  2. Hi Venkat,

    Just to update on this, I’ve found an open source tool named ELMAH which i found very useful for Exception handling and logging.

    Thanks,
    Rohan

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.