Skip to content

Perl: Print Internal Server Errors to the Browser

So, you’re a Perl programmer developing a CGI web application, chances are you’re going to make some mistakes and need to debug your code. By default, when a Perl program fails to compile or encounters a runtime error you will see your servers default HTTP 500 error message.

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Not terribly helpful or enlightening – so what do you do? Well, you can sit with a terminal window open tailing the http error log as you refresh the page to find out:

-$ tail -f error.log

But that’s a slow and painful experience. What we really want is to print the error message straight to the browser whilst we are developing. In steps the CGI::Carp module:

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

print "Content-type: text/html/n/n";
print "<h1>Hello World </h1
print "I wont work";

The fatalsToBrowser function will take over and print the error message straight to the browser window:

Software error:

syntax error at dummy.cgi line 9, near "print
Execution of dummy.cgi aborted due to compilation errors.

This is a much more useful error message and will help with debugging. Remember to remove the fatalsToBrowser call before releasing your application to production else you could potentially expose sensitive details to hackers.