ASP.NET Catch All Errors at application level

How Can We catch all the errors of an Application in one place in asp.net?
No separate Try catch blocks please!!!!!
is there any method for that?
please let me know..

Questions by rajkasa   answers by rajkasa

Showing Answers 1 - 1 of 1 Answers

just create an error page,  on application events , application_error just redirect to this error page , this eliminates the usuage of try and catch in every web application

  Was this answer useful?  Yes

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:
Include this method in ErrHandler.cs
public static void WriteError(string errorMessage)
    {
        try
        {
            string path = "~/Error/" + DateTime.Today.ToString("dd-mm-yy") +".txt";
            if(!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
               File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
            }
            using (StreamWriter w =File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                w.WriteLine("rnLog Entry : ");
                w.WriteLine("{0}",DateTime.Now.ToString(CultureInfo.InvariantCulture));
                string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
                              ". Error Message:" + errorMessage;
                w.WriteLine(err);
                w.WriteLine("__________________________");
                w.Flush();
                w.Close();
            }
        }
        catch (Exception ex)
        {
            WriteError(ex.Message);
        }

//In Global.asax.cs
 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);       
    }
Thats it you are done.
Hope this helps.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions