Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending an email when an Exception is Thrown

I have written a java class where if a method throws an exception, an email is sent, via java mail, with a report to the administrators.

It works - my question is w.r.t elegance - to catch the exception thrown by the main method, the sendEmail() method resides in the catch block of the main method. The sendEmail() method has its own try-catch block.

In effect - it looks like below - is there a more beautiful way of writing this?

try {  
    foo;  
}  
catch {  
   try{  
    sendEmail();  
  }  
  catch {  
   log(e.message);  
  }  
}  
like image 499
user353829 Avatar asked May 30 '10 01:05

user353829


1 Answers

If you want something "more elegant", one simple suggestion is to have your sendEmail helper method catch and log the email exceptions. (I don't imagine you want the exceptions to propagate ... or do some other recovery ...)


However, there is something more important to say. What you are implementing here is the wrong approach to reporting errors.

  • If something goes badly wrong with your application there is a chance that you will SPAM the administrator with multiple emails reporting the same problem over, and over, and over ...

  • By sending emails from deep within your code, you are making it hard for the administrator to integrate your application's error reporting.

A better approach is to report the problem via a Java logging frame such as Log4J. If the administrator wants to he / she can configure some kind of monitoring system like LogWatch, Nagios, etc, etc. Such a monitoring system will detect and classify errors, anomalies, etc (like your application's errors) in the various logger streams, de-dup them, and if the administrator configures it send a notification via email, pager or whatever.

like image 197
Stephen C Avatar answered Oct 23 '22 07:10

Stephen C