I would like to know if there is any way for when my system throws some kind of Exception it will only recover and send me an email informing where it occurred and which Exception was released!
I would like to know if there is any way for when my system throws some kind of Exception it will only recover and send me an email informing where it occurred and which Exception was released!
ASP.NET captures unhandled exceptions and makes them available for handling at Event Error of HttpApplication class (which represents the ASP.NET application).
In most cases these exceptions are innocuous to the application, but this does not mean that the application recovers automatically.
ASP.NET has an infrastructure for publishing such (and other) events. Through health monitoring can be published events for the most varied media such as Event Log , database e-mail and other . And if the intended provider exists, you can always implement a provider custom .
The advantage of registering events in this way is that their registration and publication is configurable, and the application does not get caught up in any specific implementation. The same event can even be published to different destinations / providers.
My recommendation is never to do this directly in the application handling the Error event.
You can use the System.Net class. Mail to send an email. To do this, include it in your Global.asax
:
using System.Net.Mail;
And use the following code:
void Application_Error(Object sender, EventArgs e)
{
/*Obter último erro do servidor e passar a
exception como parâmetro do método usado para enviar o e-mail:*/
Exception ex = Server.GetLastError();
EmailException(ex);
}
private void EmailException(Exception ex)
{
MailMessage mensagem = new MailMessage();
mensagem.To.Add("[email protected]");
mensagem.From = new MailAddress("[email protected]");
mensagem.Subject = "Assunto do e-mail";
mensagem.Body = ex.ToString(); //Definindo a exception como corpo do e-mail.
SmtpClient smtp = new SmtpClient();
smtp.Host = "Servidor SMTP"; //Definindo servidor smtp. Ex: smtp.gmail.com
smtp.Send(mensagem); //Envia o e-mail.
}
Note: If your hosting provider requires authentication , add the following line before the smtp.Send(mensagem)
method:
smtp.Credentials = new System.Net.NetworkCredential("login", "senha");
Taking advantage of Paulo Morgado's settings, you could also take a look at this article from How to send email for health monitoring notifications .