Mike Gossland's Perl Tutorial Course for Windows


Intro to GET | CGI Module | Handling Forms | Form Errors | Fatal Errors


Chapter 6. The CGI Module

Handling Fatal Errors in the Browser

Quite often when a script doesn't work, you get a completely blank page in response. Even if you have included some useful "die" messages, simply shown like this:


#!/usr/bin/perl
use CGI;

$cgi = new CGI;

print $cgi->header();
print "About to die from a fatal error of some kind<br>\n";
die "Here's a made up error";
print "Did you get the message";


You might still be looking at a blank page of output in the browser window, with no clue provided as to what went wrong. The error message from your die statement was still generated, but it went to the server log instead of the browser window.

If you are hosting on a virtual server somewhere, chances are good that you don't have access to this server log. This is unfortunate because the error messages that are stashed there can be of real help when you are trying to debug your script.

Fortunately, CGI.pm supports a method of redirecting error messages to the browser window as well as to the server log. This can be a real lifesaver if you don't have access to the error log and a nice timesaver even if you do.

To do this, you just have to invoke this desired behaviour by using Carp when you use CGI.

Here's an example of a script that does just that:


#!/usr/bin/perl
use CGI;
use CGI::Carp(fatalsToBrowser);

$cgi = new CGI;

print $cgi->header();
print "About to die from a fatal error of some kind<br>\n";
die "Here's a made up error";
print "Did you get the message";


Now if you were to run that on the perl server, you would see the die message coming to the browser window. An extra Content-Type line is printed, just in case none has been printed before. That extra line calling Carp is all it takes.

As a final example, you can see how to customize the error message that gets displayed here.


#!/usr/bin/perl
#error3.pl

use CGI;
use CGI::Carp qw(fatalsToBrowser set_message);

BEGIN {
	sub handle_errors {
		my $msg = shift;
		print "<H1>You goofed! Serves you right ";
		print "that you didn't handle your errors properly</H1>";
		print "$msg";
	}
	&set_message (\&handle_errors);
}

$cgi = new CGI;
print $cgi->header();
print "About to die from a fatal error of some kind<br>\n";
die "Here's a made up error";
print "Did you get the message";

That concludes the introduction to the CGI module. It is a large module with many, many features. You are encouraged to look into the documentation if you want to get the most you can out of it.