Handling errors and custom errors pages in ASP.Net.

August 23rd, 2007 | by programming |

Good website has to have errors handling implemented. It looks good and it’s very useful. You can set up sending emails with errors details after error occurs or save errors to database. There are three ways you can handle errors in your ASP.NET pages.

1. Page_Error Method
You can set error handling for specific page by modifing Page_Error Method:

public void Page_Error(object sender,EventArgs e)

{

    Exception objErr = Server.GetLastError().GetBaseException();

    string err =    “<b>Error Caught in Page_Error event</b><hr><br>” +

            “<br><b>Error in: </b>” + Request.Url.ToString() +

            “<br><b>Error Message: </b>” + objErr.Message.ToString()+

            “<br><b>Stack Trace:</b><br>” +

                      objErr.StackTrace.ToString();

    Response.Write(err.ToString());

    Server.ClearError();

}

2. Application_Error
To handle all errors on your website, you can use Application_Error Method in Global.asax file.

protected void Application_Error(object sender, EventArgs e)

{

    Exception objErr = Server.GetLastError().GetBaseException();

    string err =    “Error Caught in Application_Error event\n” +

            “Error in: “ + Request.Url.ToString() +

            “\nError Message:” + objErr.Message.ToString()+

            “\nStack Trace:” + objErr.StackTrace.ToString();

    EventLog.WriteEntry(“Sample_WebApp”,err,EventLogEntryType.Error);

    Server.ClearError();

    //additional actions…

}

3. Web.Config File
You can set default error pages in web.config file and then handle errors int hose websites.

<customErrors defaultRedirect=“http://hostName/applicationName/errorStatus.htm” mode=“On”>

    <error statusCode=“404″ redirect=“filenotfound.htm” />

</customErrors>

Post a Comment