8.3.2.1 The CGI::Carp.pm Module

8.3.2.1  The CGI::Carp.pm Module

  The error reported by a CGI program on the browser is quite frequently very cryptic (see Figure 8.5). It does not convey much. It sometimes seems to say that the error is really serious when it is not. In the case shown in the figure, there is nothing wrong with the manner in which the server has been configured, assuming there is a competent systems administrator. The problem here is that the server is not prepared to send out an HTML file to a browser without a proper HTTP header. The error log, quite frequently, has much more informative specification of the error. But, even the error log can sometimes lack time-stamping and may not identify which script caused it. The error that is
normally sent to the error log, can be sent to the browser as well by using the CGI::Carp.pm module discussed below.

   The CGI::Carp.pm module causes functions such as warn and die that we frequently use in Perl programs to produce time-stamped error messages so that they are useful. Most HTTP servers send STDERR, the default stream to which error messages are written, to the server’s error log. Thus, when we use CGI::Carp.pm, an error is always nicely time-stamped and always identified by the script that causes it. In addition,
CGI::Carp.pm
can ask the server to send out fatal errors such as those caused by die or other errors that terminate the program, to the Web browser. For this to happen, we must explicitly import the fatalsToBrowser subroutine.

Below is a rewrite of the program countdown.pl, now called countdownError2.pl, that uses the CGI::Carp.pm module and imports fatalToBrowser. It is exactly the same program as countdown.pl except that a syntactic error has been introduced.

 Program 8.3

#!/usr/bin/perl
#countdownError2.pl
use CGI::Carp qw(fatalsToBrowser);

print "Content-type: text/html", "\n\n";

print "", "\n;
print "Simply counting...", "\n";
print "

Simply counting...

"; print "

", "\n"; $countdown = 10; while ($countdown != 0) { print "$countdown...\n"; print "
", "\n"; --$countdown; } print "

", "\n"; Note that in the line print "", "\n;

the string containing \n is not closed with a double quote. This causes a syntactic error. Without

fatalsToBrowser, this would have resulted in an “Internal Server Error" message displayed on the browser. But, with fatalsToBrowser, the error is displayed on the browser as in Figure 8.7.

 

Figure 8.7:  Error Sent to Browser by a CGI Program

Note that it may not be appropriate to use fatalsToBrowser in a production or working system since it may give out more details to the whole world than we want. Thus, it is advisable to use it only during development, and comment out the use line when the program starts to work.