Thursday, June 12, 2008

How to send custom error message in http header from cgi script

Couple of days ago, while I was writing a CGI script in Perl, it was needed to send custom error message in http response header. I would like to share with you how I have done this.

First I have decided that for any kind of error in the code (for example, file not found, insecure path etc.) I shall return status 500 with the error message. Before this decision my code looked like this:

...
my $query = new CGI;
print $query->header(-type=>'text/plain');
...

So for any error in the script, I added the line:
print $query->header(-type=>'text/plain', -status=>"500 $err_str");
But it wasn't working. The return value (status line in the response) still '200 OK'. Then I found that query header can't be set twice (once you set it, you can't change it). Then I removed the first line print $query->header(-type=>'text/plain'); and modified the code in such a way that the header is printed once. In order to return error, I wrote a function and just called it in case of any error occurs (but I made sure the header is not printed before I call it). Here is the function:

sub catch_n_die
{

my $err_str = shift;

print $query->header(-type=>'text/plain', -status=>"500 $err_str");

exit;

}

No comments: