Public
Public
txt" If (Not File.Exists(System.Web.HttpContext.Current.Server.M apPath(path))) Then File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close() End If Using w As StreamWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)) w.WriteLine(Constants.vbCrLf & "Log Entry : ") w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)) Dim err As String = "Error in: " & System.Web.HttpContext.Current.Request.Url.ToString() & ". Error Message:" & errorMessage w.WriteLine(err) w.WriteLine("__________________________") w.Flush() w.Close() End Using Catch ex As Exception WriteError(ex.Message) End Try End Sub That was our ErrHandler class. We will now see how to use this Error Handler class and handle errors at the page level as well as at the application level. Redirecting users on unhandled errors Let us see how to catch unhandled errors and redirect the user to a different page, whenever such an unhandled error occurs 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(); // Log the error ErrHandler.WriteError(err); } 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() ' Log the error ErrHandler.WriteError(err) End Sub
We capture the error using the Server.GetLastError(). Now to redirect users to a different page whenever an unhandled error occurs, open your web.config file and locate the <customErrors> tag and uncomment it. After removing the comment, the tag will look similar to the following code: