3

In the event of an unhandled error I would like to send an email to the admin that contains the information from the error that occurred. Below is what I have in my web.config and Global.asax.cs file, the redirect works but the email does not:

<system.web>
    <customErrors mode="On" defaultRedirect="error.aspx" />
</system.web>

void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs
            // Get the exception object.
            Exception error = Server.GetLastError();

            MailMessage mail = new MailMessage();
            mail.To.Add("admin@mysite.com");
            mail.Subject = "Error";
            mail.Body = "Somebody has experienced an error." + "<br><br>";
            mail.Body += error.ToString();

            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            smtp.Credentials = new System.Net.NetworkCredential("username", "password");
            smtp.Port = 587;
            smtp.Send(mail);

            Server.ClearError();
        }
brandozz
  • 1,059
  • 6
  • 20
  • 38
  • 2
    In what way does "the email not work"? Please be more specific. – John Källén Nov 20 '13 at 20:57
  • 1
    Don't you get an exception on `smtp.Send(mail);` ? – Aage Nov 20 '13 at 20:58
  • The email is not sending and no error messages are displayed besides the default message on the error.aspx page. It almost seems as if the application redirects to the error page and does nothing with Global.asax. – brandozz Nov 20 '13 at 21:03
  • Could you check for null on your var error right after the Server.GetLastError(), this would avoid the null exception on error.ToString(). Also try to remove the defaultRedirect. – JuChom Nov 20 '13 at 21:29
  • I found this and it solved my problem, at least for now: http://stackoverflow.com/questions/343014/asp-net-custom-error-page-server-getlasterror-is-null – brandozz Nov 21 '13 at 04:37
  • For many people, standard practice is to install a module to handle emailing the developer with unhandled exceptions, such as [Elmah](http://code.google.com/p/elmah/). Are you sure it's a good idea to roll your own when other products are very simple to use? – mason Apr 14 '14 at 18:30

3 Answers3

2

Instead of rolling your own, you should install Elmah (which you can do via NuGet) and let it do the work for you. The best code is code you don't write.

Elmah is an HttpModule that sits on top of your ASP.Net stack and catches/handles uncaught exceptions:

ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.

Once ELMAH has been dropped into a running web application and configured appropriately, you get the following facilities without changing a single line of your code:

  • Logging of nearly all unhandled exceptions.
  • A web page to remotely view the entire log of recoded exceptions.
  • A web page to remotely view the full details of any one logged exception, including colored stack traces.
  • In many cases, you can review the original yellow screen of death that ASP.NET generated for a given exception, even with customErrors mode turned off.
  • An e-mail notification of each error at the time it occurs.
  • An RSS feed of the last 15 errors from the log.

Configuring Elmah to send email (on top of logging it) is pretty trivial

If you are going to write your own, install Log4Net and configure it to use 1 or more SMTP appenders in addition to whatever other log appenders you want/need/desire.

Community
  • 1
  • 1
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
0
protected void Application_Error(Object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    EmailTheException( ex );
}

private void EmailTheException( Exception ex )
{
    MailMessage mail = new MailMessage();
    mail.To = "GroupEmail@SomeCompany.com";
    mail.From = "SomeApplication@SomeCompany.com";
    mail.Subject = "An Application Exception has Occurred.";
    mail.Body = ex.ToString();

    var smtpHost = ConfigurationManager.AppSettings["smtphost"];
    var port = Convert.ToUInt32(ConfigurationManager.AppSettings["port"]);
    using (SmtpClient client = new SmtpClient(smtpHost))
    {
        if (string.IsNullOrEmpty(smtpHost)) return;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        try
        {
            client.Send(mail);
        }
        catch (SmtpException smtpEx)
        {
           //write logging code here and capture smtpEx.Message
        }
    }
}
MethodMan
  • 18,625
  • 6
  • 34
  • 52
-2

By default all uncaught exceptions will be logged into the Windows Event Log. You can access that in Control Panel->Administrative Tools->Event Viewer->Windows Logs->Application

Aron
  • 15,464
  • 3
  • 31
  • 64
  • @Kristopher and pray tell, how do you suggest one debugs the email not sending? I am good at debugging, but I can't psychic debug this problem... – Aron Apr 11 '16 at 17:55