Recipe 19.2 Redirecting Error Messages

19.2.1 Problem

You're having trouble tracking down your script's warnings and error messages, or your script's STDERR output is confusing your server.

19.2.2 Solution

Use the CGI::Carp module from the standard Perl distribution to prefix each line on STDERR with the program name and current date. You can also send warnings and errors to a file or the browser if you wish.

19.2.3 Discussion

Tracking down error messages from CGI scripts is notoriously annoying. Even if you manage to find the server error log, you still can't determine which message came from which script, or at what time. Some unfriendly web servers even abort the script if it has the audacity to emit anything out its STDERR before the Content-Type header is generated on STDOUT, so warnings can get you into trouble.

Enter the CGI::Carp module. It replaces warn and die plus the normal Carp module's carp, croak, cluck, and confess functions with more verbose and safer versions. It still sends them to the normal server error log.

use CGI::Carp; warn "This is a complaint"; die "But this one is serious";

The following use of CGI::Carp also redirects errors to a file of your choice, placed in a BEGIN block to catch compile-time warnings as well:

BEGIN {     use CGI::Carp qw(carpout);     open(LOG, ">>/var/local/cgi-logs/mycgi-log")         or die "Unable to append to mycgi-log: $!\n";     carpout(*LOG); }

You can even arrange for fatal errors to show up at the client browser, which is nice for your own debugging but might confuse the end user.

use CGI::Carp qw(fatalsToBrowser); die "Bad error here";

Even if the error happens before you get the HTTP header out, the module will try to detect this and avoid the dreaded 500 Server Error. Normal warnings still go to the server error log (or wherever you've sent them with carpout) with the program name and date stamp prepended.

19.2.4 See Also

The documentation for the standard CGI::Carp module; the discussion on BEGIN in Recipe 12.3



Perl Cookbook
Perl Cookbook, Second Edition
ISBN: 0596003137
EAN: 2147483647
Year: 2003
Pages: 501

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net