in reply to comprehensive error handling

I should probably write a Perl Monk Meditation on this subject as it seems to be coming up a lot lately and I have had to deal with this in many ways over the years.

CAVEAT:You will see some code here that has missing elements such as a lack of initialization and stuff like that. I am going to hand wave all of that so get over it.

Opening files and such

I tend to bury opening of files inside of OO modules and or subs and return the results unless the main purpose of the script is processing the file itself. (did that make sense?) For instance, here is a sniglet of code from a firewall log processor I wrote many many moons ago:

# # code preceded this.... use vars qw @ $ip_pairs @; my $ip_pairs = undef; my ($result,$message)=open_traffic_log(); if ($result){ # recovery logic goes here.... } # # more code after that... exit(0); sub open_traffic_log() { if (! open("< fwlog.txt")){ return(0,$!); } # Process log file entries here. }

That's one of many ways. Another approach that I use particulary within a CGI program.

use CGI; use CGI::Carp qw / fatalsToBrowser /; # not in production! my $cgi= new CGI; # # stuff if ( not $cgi->param('paramIReallyNeed')){ logexeception('paramIReallyNeed was missing from page'); displayExeptionPage($cgi); # Won't return... displayExceptionPage exits. } # more code follows.
With that approach I log the exception to a log file for debug purposes and the exception page actually tells the user "something really bad happened that shouldn't have and I have called for help."

Useually though I just invoke either die or carp and move on appropriately.

Other error handling

There are other types of error handling that you need to consider as well. What about a failed fork() call or socket() call?

I have sort of alluded to in a previous paragraph in this post but not spelled out the fact you also have to make the decision if a particular error is a fatal error and you need to stop execution or if it is a "soft" error that you can recover from programmatically.

Peter L. BergholdBrewer of Belgian Ales
Unix Professional