13.11. Dying Young

Perhaps the most vexing problem to deal with in CGI programming is how to handle exceptions. If something in your program dies, it (normally) prints a message to STDERR and exits. The error message doesn't look like an HTTP header, so if it comes out before you get to print the headers you'll get a 500 Server Error. And if it comes out later, it won't be in HTML (or GIF, or whatever you're outputting) and will mess up the formatting of what you're in the middle of sending.

This is mostly addressed by the CGI::Carp module. With the statement use CGI::Carp qw(fatalsToBrowser); if your program ever dies, the message will be trapped and output to the browser.[7] So, to use a short example, consider the following CGI program:

[7] If you leave out the fatalsToBrowser parameter, then output to STDERR gets identified and timestamped. This is healthy when you're using a server that sends that to the error log—you can tell what generated each message and when.

#!/usr/bin/perl -w

use strict;
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);

my ($num_angels, $pinhead_size) = (1_000_000_000, 0);

print header, start_html, h1('Philosophy 101'),

print p(<<"EOP");
Other Web sites wonder how many angels can dance on the
head of a pin; we calculate it for you.
EOP

print p('The answer is ', $num_angels/$pinhead_size);
print end_html;

This will produce something like:


Philosophy 101
Other Web sites wonder how many angels can dance on the
head of a pin; we calculate it for you
Content-type: text/html
Software error:
Illegal division by zero at /home/peter/
public_html/foo.cgi line 12.
For help, please send mail to the webmaster.

This doesn't do you much good if your program is outputting an image and has already sent the header, but fortunately the vast majority of CGI programs output HTML.

In production code, it is inadvisable to reveal error messages to end users for reasons of aesthetics and security. Randal Schwartz recently released a Linux Magazine column on a module called FatalsToEmail that e-mails errors to developers; see http://www.stonehenge.com/merlyn/LinuxMag/col14.html. See also Jonas Liljegren's CPAN module CGI::Debug at http://search.cpan.org/search?dist=CGI-Debug for some error reporting and tracing features.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset