Perl Cookbook

Perl CookbookSearch this book
Previous: 19.1. Writing a CGI ScriptChapter 19
CGI Programming
Next: 19.3. Fixing a 500 Server Error
 

19.2. Redirecting Error Messages

Problem

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

Solution

Use the CGI::Carp module from the standard Perl distribution to cause all messages going out STDERR to be prefixed with the name of the application and the current date. You can also send warnings and errors to a file or the browser if you wish.

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, which means the -w flag can get you into trouble.

Enter the CGI::Carp module. It replaces warn and die, plus the normal Carp module's carp, croak, 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 return to 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 take care of this to avoid the dreaded 500 Server Error. Normal warnings still go out to the server error log (or wherever you've sent them with carpout) with the application name and date stamp prepended.

See Also

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


Previous: 19.1. Writing a CGI ScriptPerl CookbookNext: 19.3. Fixing a 500 Server Error
19.1. Writing a CGI ScriptBook Index19.3. Fixing a 500 Server Error