Tuesday, 28 August 2012

Handle Errors in Global.asax


Let us see an example of how to use the Global.asax to catch unhandled errors that occur at the application level.
To catch unhandled errors, do the following. Add a Global.asax file (Right click project > Add New Item > Global.asax). In the Application_Error() method, add the following code:

C#
 void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs
        Exception objErr = Server.GetLastError().GetBaseException();
        string err = "Error in: " + Request.Url.ToString() +
                          ". Error Message:" + objErr.Message.ToString();
       
    }

VB.NET

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when an unhandled error occurs       
        Dim objErr As Exception = Server.GetLastError().GetBaseException()
        Dim err As String = "Error in: " & Request.Url.ToString() & ". Error Message:"& objErr.Message.ToString()
       
    End Sub

Here we make use of the Application_Error() method to capture the error using the Server.GetLastError().

No comments:

Post a Comment