How to recover from an Exception and send data from it?

Asked

Viewed 351 times

5

I wonder if there is any way for when my system launches some kind of Exception it recovers only and sends me an email stating where it occurred and which Exception was launched!

2 answers

4


ASP.NET captures the untreated exceptions and makes them available for treatment on error event of httpapplication class (representing the ASP.NET application).

In most cases these exceptions are harmless to the application, but this does not mean that the application automatically recovers.

ASP.NET has an infrastructure for the publication of this type of events (and others). Through the health Monitoring events can be published for various media such as, Event Log, database e-mail and others. And if there is the intended provider, one can always implement a tailor-made provider.

The advantage of registering events in this way is that their registration and publication is configurable, so the application is not attached to 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 dealing with the event Error.

  • 1

    That was the best answer I’ve ever seen on the subject, mainly because of the third paragraph and this excerpt: o seu registo e publicação é configurável, não ficando a aplicação agarrada a nenhuma implementação específica. +1.

3

You can use the class System.Net.Mail to send an email. For this, include it in your archive 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 method smtp.Send(mensagem):

smtp.Credentials = new System.Net.NetworkCredential("login", "senha");

Taking advantage of Paulo Morgado’s comments, you could also take a look at this article by How to email health notifications Monitoring.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.