title: Best practice error handling in Global asax
body: <p>I have code  below  in global asax  now, I want to store exception log in database, is this good practice? because if sql error happens there, I want to log it too. So I am thinking changing the code below to write text log instead email, then on sql error, write text log. </p>
  
  <pre><code>void Application_Error(object sender, EventArgs e)
   {
      // Code that runs when an unhandled error occurs
      string testEnvironment = ConfigurationSettings.AppSettings["isTestEnvironment"];
      if (testEnvironment == "0")
      {
          Exception ex = Server.GetLastError();
           if (ex is HttpException &amp;&amp; ex.InnerException is ViewStateException)
          {
            Response.Redirect(Request.Url.AbsoluteUri)                
            return
          }
          StringBuilder theBody = new StringBuilder();
          theBody.Append("URL: " + Request.Url + "\n");
          theBody.Append("Referer: " + Request.ServerVariables["HTTP_REFERER"] + "\n");
          theBody.Append("IP: " + Request.ServerVariables["REMOTE_HOST"] + "\n");
          theBody.Append("Error Message: " + ex.ToString() + "\n");
          if (User.Identity.IsAuthenticated)
              theBody.Append("User: " + User.Identity.Name + "\n");
          else
              theBody.Append("User is not logged in." + "\n");
          theBody.Append("Form Values: " + "\n");
          foreach (string s in Request.Form.AllKeys)
          {
              if (s != "__VIEWSTATE")
                  theBody.Append(s + ":" + Request.Form[s] + "\n");
          }
          theBody.Append("Session Values: " + "\n");
          foreach (string s in Session.Keys)
              theBody.Append(s + ":" + Session[s] + "\n");
          System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage();
          email.IsBodyHtml = false;
          email.From = new System.Net.Mail.MailAddress("errors@karpach.com", "ErrorManager");
          email.To.Add(new System.Net.Mail.MailAddress("errornotification@karpach.com", "Developer"));
          email.Subject = Request.Url.ToString().Split('/')[2] + " has ASP.NET error";
          email.Body = theBody.ToString();
          try
          {
              System.Net.Mail.SmtpClient emailProvider = new System.Net.Mail.SmtpClient();
              emailProvider.Send(email);
          }
          catch (Exception anException)
          {
          }
          finally
          {
              if (Request.Url.Segments[Request.Url.Segments.Length - 1].ToLower() != "error.aspx")
                  Response.Redirect("~/error.aspx?msg=4");
              else
              {
                  Response.Write(@"We encountered an internal error. We apologize for any inconvenience
                  but know that our staff gets emailed EVERY error that occurs so that we can solve it promptly.");
                  Response.End();
              }
          }
      }
   }
  </code></pre>