I am working on a script that does many things, and if at any point during its execution a 'die' gets executed or an error occurs, I'd like to send an email message to myself.
I'm currently using the END block to check the exit status, and if it is greater than 0 call a error email subroutine, but I am wondering if there is a better way. The flaw with this current implementation is that if an error occurs in the email subroutine, an infinite loop will occur.
We've really got two separate questions here:
How do you (reliably) execute code when the program dies without creating an infinite loop if this code also hits a fatal error?
What's the best way to send email from Perl code?
So, to answer each separately:
Rather than an END block, I would use a $SIG{__DIE__} handler (untested code, but should be right):
$SIG{__DIE__} = \&error_handler;
sub error_handler {
die @_ if $^S; # Do nothing if we died in an eval{}
delete $SIG{__DIE__}; # Clear handler in case following code also dies
print STDERR "Blue Wizard is about to die!\n";
}
There are, of course, many excellent mail-sending modules on CPAN. My personal preference from among them is MIME::Lite, which will send mail using sendmail by default, but, if you're on Windows or some other system with no sendmail command, you can use MIME::Lite->send("smtp"); to send via SMTP directly without going through a local MTA. There is also support for routing mail through an outgoing mail server (handy if your upstream provider blocks port 25!) and handling common authentication methods on that server if needed.
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