5 B<CGI::Carp> - CGI routines for writing to the HTTPD (or other) error log
11 croak "We're outta here!";
12 confess "It was my fault: $!";
13 carp "It was your fault!";
17 use CGI::Carp qw(cluck);
18 cluck "I wouldn't do that if I were you";
20 use CGI::Carp qw(fatalsToBrowser);
21 die "Fatal error messages are now sent to browser";
25 CGI scripts have a nasty habit of leaving warning messages in the error
26 logs that are neither time stamped nor fully identified. Tracking down
27 the script that caused the error is a pain. This fixes that. Replace
36 And the standard warn(), die (), croak(), confess() and carp() calls
37 will automagically be replaced with functions that write out nicely
38 time-stamped messages to the HTTP server error log.
42 [Fri Nov 17 21:40:43 1995] test.pl: I'm confused at test.pl line 3.
43 [Fri Nov 17 21:40:43 1995] test.pl: Got an error message: Permission denied.
44 [Fri Nov 17 21:40:43 1995] test.pl: I'm dying.
46 =head1 REDIRECTING ERROR MESSAGES
48 By default, error messages are sent to STDERR. Most HTTPD servers
49 direct STDERR to the server's error log. Some applications may wish
50 to keep private error logs, distinct from the server's error log, or
51 they may wish to direct error messages to STDOUT so that the browser
54 The C<carpout()> function is provided for this purpose. Since
55 carpout() is not exported by default, you must import it explicitly by
58 use CGI::Carp qw(carpout);
60 The carpout() function requires one argument, which should be a
61 reference to an open filehandle for writing errors. It should be
62 called in a C<BEGIN> block at the top of the CGI application so that
63 compiler errors will be caught. Example:
66 use CGI::Carp qw(carpout);
67 open(LOG, ">>/usr/local/cgi-logs/mycgi-log") or
68 die("Unable to open mycgi-log: $!\n");
72 carpout() does not handle file locking on the log for you at this point.
73 Also, note that carpout() does not work with in-memory file handles, although
74 a patch would be welcome to address that.
76 The real STDERR is not closed -- it is moved to CGI::Carp::SAVEERR. Some
77 servers, when dealing with CGI scripts, close their connection to the
78 browser when the script closes STDOUT and STDERR. CGI::Carp::SAVEERR is there to
79 prevent this from happening prematurely.
81 You can pass filehandles to carpout() in a variety of ways. The "correct"
82 way according to Tom Christiansen is to pass a reference to a filehandle
87 This looks weird to mere mortals however, so the following syntaxes are
94 carpout(\'main::LOG');
98 FileHandle and other objects work as well.
100 Use of carpout() is not great for performance, so it is recommended
101 for debugging purposes or for moderate-use applications. A future
102 version of this module may delay redirecting STDERR until one of the
103 CGI::Carp methods is called to prevent the performance hit.
105 =head1 MAKING PERL ERRORS APPEAR IN THE BROWSER WINDOW
107 If you want to send fatal (die, confess) errors to the browser, ask to
108 import the special "fatalsToBrowser" subroutine:
110 use CGI::Carp qw(fatalsToBrowser);
111 die "Bad error here";
113 Fatal errors will now be echoed to the browser as well as to the log. CGI::Carp
114 arranges to send a minimal HTTP header to the browser so that even errors that
115 occur in the early compile phase will be seen.
116 Nonfatal errors will still be directed to the log file only (unless redirected
119 Note that fatalsToBrowser does B<not> work with mod_perl version 2.0
122 =head2 Changing the default message
124 By default, the software error message is followed by a note to
125 contact the Webmaster by e-mail with the time and date of the error.
126 If this message is not to your liking, you can change it using the
127 set_message() routine. This is not imported by default; you should
128 import it on the use() line:
130 use CGI::Carp qw(fatalsToBrowser set_message);
131 set_message("It's not a bug, it's a feature!");
133 You may also pass in a code reference in order to create a custom
134 error message. At run time, your code will be called with the text
135 of the error message that caused the script to die. Example:
137 use CGI::Carp qw(fatalsToBrowser set_message);
141 print "<h1>Oh gosh</h1>";
142 print "<p>Got an error: $msg</p>";
144 set_message(\&handle_errors);
147 In order to correctly intercept compile-time errors, you should call
148 set_message() from within a BEGIN{} block.
150 =head1 DOING MORE THAN PRINTING A MESSAGE IN THE EVENT OF PERL ERRORS
152 If fatalsToBrowser in conjunction with set_message does not provide
153 you with all of the functionality you need, you can go one step
154 further by specifying a function to be executed any time a script
155 calls "die", has a syntax error, or dies unexpectedly at runtime
156 with a line like "undef->explode();".
158 use CGI::Carp qw(set_die_handler);
162 print "content-type: text/html\n\n";
163 print "<h1>Oh gosh</h1>";
164 print "<p>Got an error: $msg</p>";
166 #proceed to send an email to a system administrator,
167 #write a detailed message to the browser and/or a log,
170 set_die_handler(\&handle_errors);
173 Notice that if you use set_die_handler(), you must handle sending
174 HTML headers to the browser yourself if you are printing a message.
176 If you use set_die_handler(), you will most likely interfere with
177 the behavior of fatalsToBrowser, so you must use this or that, not
180 Using set_die_handler() sets SIG{__DIE__} (as does fatalsToBrowser),
181 and there is only one SIG{__DIE__}. This means that if you are
182 attempting to set SIG{__DIE__} yourself, you may interfere with
183 this module's functionality, or this module may interfere with
184 your module's functionality.
186 =head1 MAKING WARNINGS APPEAR AS HTML COMMENTS
188 It is now also possible to make non-fatal errors appear as HTML
189 comments embedded in the output of your program. To enable this
190 feature, export the new "warningsToBrowser" subroutine. Since sending
191 warnings to the browser before the HTTP headers have been sent would
192 cause an error, any warnings are stored in an internal buffer until
193 you call the warningsToBrowser() subroutine with a true argument:
195 use CGI::Carp qw(fatalsToBrowser warningsToBrowser);
196 use CGI qw(:standard);
198 warningsToBrowser(1);
200 You may also give a false argument to warningsToBrowser() to prevent
201 warnings from being sent to the browser while you are printing some
202 content where HTML comments are not allowed:
204 warningsToBrowser(0); # disable warnings
205 print "<script type=\"text/javascript\"><!--\n";
206 print_some_javascript_code();
207 print "//--></script>\n";
208 warningsToBrowser(1); # re-enable warnings
210 Note: In this respect warningsToBrowser() differs fundamentally from
211 fatalsToBrowser(), which you should never call yourself!
213 =head1 OVERRIDING THE NAME OF THE PROGRAM
215 CGI::Carp includes the name of the program that generated the error or
216 warning in the messages written to the log and the browser window.
217 Sometimes, Perl can get confused about what the actual name of the
218 executed program was. In these cases, you can override the program
219 name that CGI::Carp will use for all messages.
221 The quick way to do that is to tell CGI::Carp the name of the program
222 in its use statement. You can do that by adding
223 "name=cgi_carp_log_name" to your "use" statement. For example:
225 use CGI::Carp qw(name=cgi_carp_log_name);
227 . If you want to change the program name partway through the program,
228 you can use the C<set_progname()> function instead. It is not
229 exported by default, you must import it explicitly by saying
231 use CGI::Carp qw(set_progname);
233 Once you've done that, you can change the logged name of the program
234 at any time by calling
236 set_progname(new_program_name);
238 You can set the program back to the default by calling
242 Note that this override doesn't happen until after the program has
243 compiled, so any compile-time errors will still show up with the
244 non-overridden program name
248 1.29 Patch from Peter Whaite to fix the unfixable problem of CGI::Carp
249 not behaving correctly in an eval() context.
251 1.05 carpout() added and minor corrections by Marc Hedlund
252 <hedlund@best.com> on 11/26/95.
254 1.06 fatalsToBrowser() no longer aborts for fatal errors within
257 1.08 set_message() added and carpout() expanded to allow for FileHandle
260 1.09 set_message() now allows users to pass a code REFERENCE for
261 really custom error messages. croak and carp are now
262 exported by default. Thanks to Gunther Birznieks for the
265 1.10 Patch from Chris Dean (ctdean@cogit.com) to allow
266 module to run correctly under mod_perl.
268 1.11 Changed order of > and < escapes.
270 1.12 Changed die() on line 217 to CORE::die to avoid B<-w> warning.
272 1.13 Added cluck() to make the module orthogonal with Carp.
273 More mod_perl related fixes.
275 1.20 Patch from Ilmari Karonen (perl@itz.pp.sci.fi): Added
276 warningsToBrowser(). Replaced <CODE> tags with <PRE> in
277 fatalsToBrowser() output.
279 1.23 ineval() now checks both $^S and inspects the message for the "eval" pattern
280 (hack alert!) in order to accommodate various combinations of Perl and
283 1.24 Patch from Scott Gifford (sgifford@suspectclass.com): Add support
284 for overriding program name.
286 1.26 Replaced CORE::GLOBAL::die with the evil $SIG{__DIE__} because the
287 former isn't working in some people's hands. There is no such thing
288 as reliable exception handling in Perl.
290 1.27 Replaced tell STDOUT with bytes=tell STDOUT.
294 Copyright 1995-2002, Lincoln D. Stein. All rights reserved.
296 This library is free software; you can redistribute it and/or modify
297 it under the same terms as Perl itself.
299 Address bug reports and comments to: lstein@cshl.org
303 Carp, CGI::Base, CGI::BasePlus, CGI::Request, CGI::MiniSvr, CGI::Form,
313 *CORE::GLOBAL::die = \&CGI::Carp::die;
319 @EXPORT = qw(confess croak carp);
320 @EXPORT_OK = qw(carpout fatalsToBrowser warningsToBrowser wrap set_message set_die_handler set_progname cluck ^name= die);
322 $main::SIG{__WARN__}=\&CGI::Carp::warn;
324 $CGI::Carp::VERSION = '3.45';
325 $CGI::Carp::CUSTOM_MSG = undef;
326 $CGI::Carp::DIE_HANDLER = undef;
329 # fancy import routine detects and handles 'errorWrap' specially.
334 if (@name=grep(/^name=/,@_))
336 my($n) = (split(/=/,$name[0]))[1];
338 @_=grep(!/^name=/,@_);
341 grep($routines{$_}++,@_,@EXPORT);
342 $WRAP++ if $routines{'fatalsToBrowser'} || $routines{'wrap'};
343 $WARN++ if $routines{'warningsToBrowser'};
344 my($oldlevel) = $Exporter::ExportLevel;
345 $Exporter::ExportLevel = 1;
346 Exporter::import($pkg,keys %routines);
347 $Exporter::ExportLevel = $oldlevel;
348 $main::SIG{__DIE__} =\&CGI::Carp::die if $routines{'fatalsToBrowser'};
349 # $pkg->export('CORE::GLOBAL','die');
352 # These are the originals
353 sub realwarn { CORE::warn(@_); }
354 sub realdie { CORE::die(@_); }
358 my($pack,$file,$line,$sub) = caller($level);
359 my($dev,$dirs,$id) = File::Spec->splitpath($file);
360 return ($file,$line,$id);
364 my $time = scalar(localtime);
366 my ($id,$pack,$file,$dev,$dirs);
367 if (defined($CGI::Carp::PROGNAME)) {
368 $id = $CGI::Carp::PROGNAME;
372 ($pack,$file) = caller($frame++);
375 ($dev,$dirs,$id) = File::Spec->splitpath($id);
376 return "[$time] $id: ";
380 $CGI::Carp::PROGNAME = shift;
381 return $CGI::Carp::PROGNAME;
387 my($file,$line,$id) = id(1);
388 $message .= " at $file line $line.\n" unless $message=~/\n$/;
389 _warn($message) if $WARN;
391 $message=~s/^/$stamp/gm;
397 if ($EMIT_WARNINGS) {
398 # We need to mangle the message a bit to make it a valid HTML
399 # comment. This is done by substituting similar-looking ISO
400 # 8859-1 characters for <, > and -. This is a hack.
401 $msg =~ tr/<>-/\253\273\255/;
403 print STDOUT "<!-- warning: $msg -->\n";
405 push @WARNINGS, $msg;
410 # The mod_perl package Apache::Registry loads CGI programs by calling
411 # eval. These evals don't count when looking at the stack backtrace.
413 my $message = Carp::longmess();
414 $message =~ s,eval[^\n]+(ModPerl|Apache)/(?:Registry|Dispatch)\w*\.pm.*,,s
415 if exists $ENV{MOD_PERL};
420 (exists $ENV{MOD_PERL} ? 0 : $^S) || _longmess() =~ /eval [\{\']/m
424 my ($arg,@rest) = @_;
426 &$DIE_HANDLER($arg,@rest) if $DIE_HANDLER;
428 # if called as die( $object, 'string' ),
429 # all is stringified, just like with
431 $arg = join '' => "$arg", @rest if @rest;
435 my($file,$line,$id) = id(1);
437 $arg .= " at $file line $line.\n" unless ref $arg or $arg=~/\n$/;
439 realdie $arg if ineval();
440 &fatalsToBrowser($arg) if $WRAP;
442 $arg=~s/^/ stamp() /gme if $arg =~ /\n$/ or not exists $ENV{MOD_PERL};
444 $arg .= "\n" unless $arg =~ /\n$/;
450 $CGI::Carp::CUSTOM_MSG = shift;
451 return $CGI::Carp::CUSTOM_MSG;
454 sub set_die_handler {
456 my ($handler) = shift;
458 #setting SIG{__DIE__} here is necessary to catch runtime
459 #errors which are not called by literally saying "die",
460 #such as the line "undef->explode();". however, doing this
461 #will interfere with fatalsToBrowser, which also sets
462 #SIG{__DIE__} in the import() function above (or the
463 #import() function above may interfere with this). for
464 #this reason, you should choose to either set the die
465 #handler here, or use fatalsToBrowser, not both.
466 $main::SIG{__DIE__} = $handler;
468 $CGI::Carp::DIE_HANDLER = $handler;
470 return $CGI::Carp::DIE_HANDLER;
473 sub confess { CGI::Carp::die Carp::longmess @_; }
474 sub croak { CGI::Carp::die Carp::shortmess @_; }
475 sub carp { CGI::Carp::warn Carp::shortmess @_; }
476 sub cluck { CGI::Carp::warn Carp::longmess @_; }
478 # We have to be ready to accept a filehandle as a reference
482 my($no) = fileno(to_filehandle($in));
483 realdie("Invalid filehandle $in\n") unless defined $no;
485 open(SAVEERR, ">&STDERR");
486 open(STDERR, ">&$no") or
487 ( print SAVEERR "Unable to redirect STDERR: $!\n" and exit(1) );
490 sub warningsToBrowser {
491 $EMIT_WARNINGS = @_ ? shift : 1;
492 _warn(shift @WARNINGS) while $EMIT_WARNINGS and @WARNINGS;
496 sub fatalsToBrowser {
499 $msg = "$msg" if ref $msg;
506 my($wm) = $ENV{SERVER_ADMIN} ?
507 qq[the webmaster (<a href="mailto:$ENV{SERVER_ADMIN}">$ENV{SERVER_ADMIN}</a>)] :
508 "this site's webmaster";
509 my ($outer_message) = <<END;
510 For help, please send mail to $wm, giving this error message
511 and the time and date of the error.
514 my $mod_perl = exists $ENV{MOD_PERL};
517 if (ref($CUSTOM_MSG) eq 'CODE') {
518 print STDOUT "Content-type: text/html\n\n"
521 &$CUSTOM_MSG($msg); # nicer to perl 5.003 users
523 if ($@) { print STDERR q(error while executing the error handler: $@); }
527 $outer_message = $CUSTOM_MSG;
532 <h1>Software error:</h1>
542 if ($ENV{MOD_PERL_API_VERSION} && $ENV{MOD_PERL_API_VERSION} == 2) {
544 require Apache2::RequestRec;
545 require Apache2::RequestIO;
546 require Apache2::RequestUtil;
548 require ModPerl::Util;
549 require Apache2::Response;
550 $r = Apache2::RequestUtil->request;
553 $r = Apache->request;
555 # If bytes have already been sent, then
556 # we print the message out directly.
557 # Otherwise we make a custom error
558 # handler to produce the doc for us.
559 if ($r->bytes_sent) {
561 $mod_perl == 2 ? ModPerl::Util::exit(0) : $r->exit;
563 # MSIE won't display a custom 500 response unless it is >512 bytes!
564 if ($ENV{HTTP_USER_AGENT} =~ /MSIE/) {
565 $mess = "<!-- " . (' ' x 513) . " -->\n$mess";
567 $r->custom_response(500,$mess);
570 my $bytes_written = eval{tell STDOUT};
571 if (defined $bytes_written && $bytes_written > 0) {
575 print STDOUT "Status: 500\n";
576 print STDOUT "Content-type: text/html\n\n";
581 warningsToBrowser(1); # emit warnings before dying
584 # Cut and paste from CGI.pm so that we don't have the overhead of
585 # always loading the entire CGI module.
588 return undef unless $thingy;
589 return $thingy if UNIVERSAL::isa($thingy,'GLOB');
590 return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
593 while (my $package = caller($caller++)) {
594 my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy";
595 return $tmp if defined(fileno($tmp));