Failing gracefully with CGI::Carp

The errors given in the web server's error logs are not always easy to read and understand. To make life easier, we can use a Perl module called CGI::Carp to add timestamps and other handy information to the logs.

use CGI::Carp;

We can also make our errors go to a separate log, by using the carpout part of the module. This needs to be done inside a BEGIN block in order to catch compiler errors as well as ones which occur at the interpretation stage.

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

Lastly, we can cause any fatal errors to have their error messages and diagnostic information output directly to the browser:

use CGI::Carp 'fatalsToBrowser';

You may also like to look at the equivalent module for non-CGI scripts, the basic Carp module, which is documented on page 385 of your Camel book.

Exercise

  1. Use the CGI::Carp module in one of your scripts

  2. Deliberately cause a syntax error, for instance by removing a semi-colon or quote mark, or inserting a die ("Argh!"); statement, and see what happens