in reply to Proper use of CGI::Carp together with CGI.pm

Your last code example is fine. It doesn't use global variables, since $q is declared as lexical by my. In effect, your carp_error subroutine is acting as a closure. In fact, you could go all the way and create your error-handling routine as an anonymous subroutine. That way it won't stay around cluttering your symbol tables.

You also don't need to create your CGI object in a BEGIN block, as long as you make sure your error handler has some CGI object available. In my code example below, the line marked with "!!!" does that. Note the brackets ({}) on that line -- they make the "backup" CGI object completely independent from the actual HTTP request. That way, if your script dies because of a malformed request, it hopefully will still be able to generate its error message.

use CGI::Carp qw( fatalsToBrowser ); use CGI qw( -headers_once ); my $q = new CGI; BEGIN { CGI::Carp::set_message sub { my $error = shift; $q ||= new CGI {}; # !!! print $q->header(), $q->start_html( "Error" ), $q->h1( "Error" ), $q->p( "Sorry, the following error occurred:" ), $q->pre( $q->i( $error ) ), $q->end_html(); }; }

Also worth noting in the use of $q->pre() for the actual error. Perl error messages are preformatted with indents and line breaks, and look rather messy if smashed up in a single HTML paragraph.

Now, once you've gone to all that trouble and finally test your code, you will notice that you're still sending double HTTP headers. Why? Well, there's this little detail in the CGI::Carp documentation:

CGI::Carp arranges to send a minimal HTTP header to the browser so that even errors that occur in the early compile phase will be seen.

Damn. Time to submit a patch, I guess. Meanwhile, I suppose you can work around the issue by inserting the following lines at the end of the BEGIN block:

## REALLY UGLY KLUGE FOLLOWS, USE AT YOUR OWN RISK: my $fatalsToBrowser = \&CGI::Carp::fatalsToBrowser; no warnings 'redefine'; *CGI::Carp::fatalsToBrowser = sub { local $ENV{GATEWAY_INTERFACE} = "CGI-PerlEx-FAKE"; &$fatalsToBrowser; }

Replies are listed 'Best First'.
Re: Re: Proper use of CGI::Carp together with CGI.pm
by iltzu (Initiate) on Oct 14, 2003 at 22:25 UTC
    Addendum: I've just sent a patch to fix this to Lincoln Stein. Wait and see.