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("[email protected]");
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With