This block intercepts perl errors and sets an error handler to determine where to send the output. If the user has a cookie named "debug" and it's value is "true", then errors go to the browser (and stderr is redirected to /dev/null). Otherwise, errors are appended to a file that I can browse later. (The file is uniquely named using the IP address of the browser that triggered the error.)
BEGIN { use CGI::Carp qw(fatalsToBrowser set_message); sub handle_error { use CGI; use CGI::Carp qw(carpout); $query = new CGI; $debug = $query->cookie('debug') || "unknown"; if ($debug eq "true") { carpout(LOG) if open(LOG, ">/dev/null"); $msg = shift; print "<h1>Script Error:</h1>\n\n"; $msg =~ s/\n/<br>/g; } else { if (open FILE, "../web-banner2") { print <FILE>; close FIL +E; } $remote_addr = $ENV{'REMOTE_ADDR'}; if (open FILE, "+>>tmp/$remote_addr") { print FILE "Script Error: " . localtime(time()); print FILE qq( Address: $remote_addr Referrer: $ENV{HTTP_REFERER} ===========\n); carpout(FILE); print FILE "===============\n\n"; close FILE; } else { print "Note: can't open error log: $!<br>\n"; } $msg = qq(<h1>Software Error!</h1> Please <a href="mailto:argv@danheller.com">send me mail</a>.); } print $msg; } set_message(\&handle_error); }
The new question revolves around the length of this block and the best place to put it. I have many perl scripts that run my site, and I don't want to copy this code redundantly at the top of each one. So, I made a module called that I "include" (via use) at the top of each perl script.
The questions are, first, it seems odd to have an entire module that contains nothing but a BEGIN block. Is that an appropriate way to handle all this? Also, would this interfere with other BEGIN blocks in other places in ways not apparent with simple testing?
In reply to Where to put long BEGIN blocks used by many programs... by argv
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |