3 # Copyright (c) 1997-8 Graham Barr <gbarr@ti.com>. All rights reserved.
4 # This program is free software; you can redistribute it and/or
5 # modify it under the same terms as Perl itself.
7 # Based on my original Error.pm, and Exceptions.pm by Peter Seibel
8 # <peter@weblogic.com> and adapted by Jesse Glick <jglick@sig.bsh.com>.
10 # but modified ***significantly***
17 use vars
qw($VERSION);
25 'bool' => sub { return 1; },
29 $Error::Depth = 0; # Depth to pass to caller()
30 $Error::Debug = 0; # Generate verbose stack traces
31 @Error::STACK = (); # Clause stack for try
32 $Error::THROWN = undef; # last error thrown, a workaround until die $ref works
34 my $LAST; # Last error created
35 my %ERROR; # Last error associated with package
37 sub _throw_Error_Simple
40 return Error::Simple->new($args->{'text'});
43 $Error::ObjectifyCallback = \&_throw_Error_Simple;
46 # Exported subs are defined in Error::subs
53 local $Exporter::ExportLevel = $Exporter::ExportLevel + 1;
56 if( $_ eq ':warndie' ) {
57 Error::WarnDie->import();
65 Error::subs->import(@tags);
68 # I really want to use last for the name of this method, but it is a keyword
69 # which prevent the syntax last Error
74 return $LAST unless @_;
77 return exists $ERROR{$pkg} ? $ERROR{$pkg} : undef
82 if($obj->isa('HASH')) {
83 $err = $obj->{'__Error__'}
84 if exists $obj->{'__Error__'};
86 elsif($obj->isa('GLOB')) {
87 $err = ${*$obj}{'__Error__'}
88 if exists ${*$obj}{'__Error__'};
103 return unless ref($pkg);
105 undef $ERROR{$pkg} if defined $ERROR{$pkg};
108 # Return as much information as possible about where the error
109 # happened. The -stacktrace element only exists if $Error::DEBUG
110 # was set when the error was created
115 return $self->{'-stacktrace'}
116 if exists $self->{'-stacktrace'};
118 my $text = exists $self->{'-text'} ? $self->{'-text'} : "Died";
120 $text .= sprintf(" at %s line %d.\n", $self->file, $self->line)
121 unless($text =~ /\n$/s);
131 return unless ref($obj);
133 if($obj->isa('HASH')) {
134 $obj->{'__Error__'} = $err;
136 elsif($obj->isa('GLOB')) {
137 ${*$obj}{'__Error__'} = $err;
140 $ERROR{ ref($obj) } = $err;
148 my($pkg,$file,$line) = caller($Error::Depth);
157 $err->associate($err->{'-object'})
158 if(exists $err->{'-object'});
160 # To always create a stacktrace would be very inefficient, so
161 # we only do it if $Error::Debug is set
165 local $Carp::CarpLevel = $Error::Depth;
166 my $text = defined($err->{'-text'}) ? $err->{'-text'} : "Error";
167 my $trace = Carp::longmess($text);
168 # Remove try calls from the trace
169 $trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
170 $trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::run_clauses[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
171 $err->{'-stacktrace'} = $trace
174 $@ = $LAST = $ERROR{$pkg} = $err;
177 # Throw an error. this contains some very gory code.
181 local $Error::Depth = $Error::Depth + 1;
183 # if we are not rethrow-ing then create the object to throw
184 $self = $self->new(@_) unless ref($self);
186 die $Error::THROWN = $self;
189 # syntactic sugar for
191 # die with Error( ... );
195 local $Error::Depth = $Error::Depth + 1;
200 # syntactic sugar for
202 # record Error( ... ) and return;
206 local $Error::Depth = $Error::Depth + 1;
213 # try { ... } catch CLASS with { ... }
218 my $clauses = shift || {};
219 my $catch = $clauses->{'catch'} ||= [];
221 unshift @$catch, $pkg, $code;
226 # Object query methods
230 exists $self->{'-object'} ? $self->{'-object'} : undef;
235 exists $self->{'-file'} ? $self->{'-file'} : undef;
240 exists $self->{'-line'} ? $self->{'-line'} : undef;
245 exists $self->{'-text'} ? $self->{'-text'} : undef;
252 defined $self->{'-text'} ? $self->{'-text'} : "Died";
257 exists $self->{'-value'} ? $self->{'-value'} : undef;
260 package Error::Simple;
262 use vars qw($VERSION);
264 $VERSION = "0.17025";
266 @Error::Simple::ISA = qw(Error);
270 my $text = "" . shift;
274 local $Error::Depth
= $Error::Depth
+ 1;
276 @args = ( -file
=> $1, -line
=> $2)
277 if($text =~ s/\s+at\s+(\S+)\s+line\s+(\d+)(?:,\s*<[^>]*>\s+line\s+\d+)?\.?\n?$//s);
278 push(@args, '-value', 0 + $value)
281 $self->SUPER::new
(-text
=> $text, @args);
286 my $text = $self->SUPER::stringify
;
287 $text .= sprintf(" at %s line %d.\n", $self->file, $self->line)
288 unless($text =~ /\n$/s);
292 ##########################################################################
293 ##########################################################################
295 # Inspired by code from Jesse Glick <jglick@sig.bsh.com> and
296 # Peter Seibel <peter@weblogic.com>
301 use vars
qw(@EXPORT_OK @ISA %EXPORT_TAGS);
303 @EXPORT_OK = qw(try with finally except otherwise);
304 %EXPORT_TAGS = (try
=> \
@EXPORT_OK);
308 sub run_clauses
($$$\@
) {
309 my($clauses,$err,$wantarray,$result) = @_;
312 $err = $Error::ObjectifyCallback
->({'text' =>$err}) unless ref($err);
318 if(defined($catch = $clauses->{'catch'})) {
322 for( ; $i < @
$catch ; $i += 2) {
323 my $pkg = $catch->[$i];
324 unless(defined $pkg) {
326 splice(@
$catch,$i,2,$catch->[$i+1]->($err));
330 elsif(Scalar
::Util
::blessed
($err) && $err->isa($pkg)) {
331 $code = $catch->[$i+1];
334 local($Error::THROWN
, $@
);
338 @
{$result} = $code->($err,\
$more);
340 elsif(defined($wantarray)) {
342 $result->[0] = $code->($err,\
$more);
345 $code->($err,\
$more);
350 next CATCHLOOP
if $more;
354 $err = $@
|| $Error::THROWN
;
355 $err = $Error::ObjectifyCallback
->({'text' =>$err})
366 if(defined($owise = $clauses->{'otherwise'})) {
367 my $code = $clauses->{'otherwise'};
369 local($Error::THROWN
, $@
);
373 @
{$result} = $code->($err,\
$more);
375 elsif(defined($wantarray)) {
377 $result->[0] = $code->($err,\
$more);
380 $code->($err,\
$more);
388 $err = $@
|| $Error::THROWN
;
390 $err = $Error::ObjectifyCallback
->({'text' =>$err})
400 my $clauses = @_ ?
shift : {};
405 unshift @Error::STACK
, $clauses;
407 my $wantarray = wantarray();
410 local $Error::THROWN
= undef;
417 elsif(defined $wantarray) {
418 $result[0] = $try->();
426 $err = $@
|| $Error::THROWN
432 $err = run_clauses
($clauses,$err,wantarray,@result)
435 $clauses->{'finally'}->()
436 if(defined($clauses->{'finally'}));
440 if (Scalar
::Util
::blessed
($err) && $err->can('throw'))
450 wantarray ?
@result : $result[0];
453 # Each clause adds a sub to the list of clauses. The finally clause is
454 # always the last, and the otherwise clause is always added just before
455 # the finally clause.
457 # All clauses, except the finally clause, add a sub which takes one argument
458 # this argument will be the error being thrown. The sub will return a code ref
459 # if that clause can handle that error, otherwise undef is returned.
461 # The otherwise clause adds a sub which unconditionally returns the users
462 # code reference, this is why it is forced to be last.
464 # The catch clause is defined in Error.pm, as the syntax causes it to
465 # be called as a method
473 my $clauses = { 'finally' => $code };
477 # The except clause is a block which returns a hashref or a list of
478 # key-value pairs, where the keys are the classes and the values are subs.
482 my $clauses = shift || {};
483 my $catch = $clauses->{'catch'} ||= [];
487 my(@array) = $code->($_[0]);
488 if(@array == 1 && ref($array[0])) {
491 if(UNIVERSAL
::isa
($ref,'HASH'));
499 unshift @
{$catch}, undef, $sub;
504 sub otherwise
(&;$) {
506 my $clauses = shift || {};
508 if(exists $clauses->{'otherwise'}) {
510 Carp
::croak
("Multiple otherwise clauses");
513 $clauses->{'otherwise'} = $code;
520 package Error
::WarnDie
;
527 local $Carp::CarpLevel
= $start;
528 my $trace = Carp
::longmess
("");
529 # Remove try calls from the trace
530 $trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
531 $trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::run_clauses[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
532 my @callstack = split( m/\n/, $trace );
543 local $SIG{__DIE__
} = $old_DIE if( defined $old_DIE );
547 my ( $etype, $message, $location, @callstack );
548 if ( ref($e) && $e->isa( "Error" ) ) {
549 $etype = "exception of type " . ref( $e );
551 $location = $e->file . ":" . $e->line;
552 @callstack = split( m/\n/, $e->stacktrace );
555 # Don't apply subsequent layer of message formatting
556 die $e if( $e =~ m/^\nUnhandled perl error caught at toplevel:\n\n/ );
557 $etype = "perl error";
559 while( caller( $stackdepth ) =~ m/^Error(?:$|::)/ ) {
563 @callstack = gen_callstack
( $stackdepth + 1 );
568 if ( $message =~ s/ at (.*?) line (\d+)\.$// ) {
569 $location = $1 . ":" . $2;
572 my @caller = caller( $stackdepth );
573 $location = $caller[1] . ":" . $caller[2];
578 # Do it this way in case there are no elements; we don't print a spurious \n
579 my $callstack = join( "", map { "$_\n"} @callstack );
581 die "\nUnhandled $etype caught at toplevel:\n\n $message\n\nThrown from: $location\n\nFull stack trace:\n\n$callstack\n";
586 my ( $message ) = @_;
588 local $SIG{__WARN__
} = $old_WARN if( defined $old_WARN );
590 $message =~ s/ at .*? line \d+\.$//;
593 my @callstack = gen_callstack
( 1 );
594 my $location = shift @callstack;
596 # $location already starts in a leading space
597 $message .= $location;
599 # Do it this way in case there are no elements; we don't print a spurious \n
600 my $callstack = join( "", map { "$_\n"} @callstack );
602 warn "$message:\n$callstack";
607 $old_DIE = $SIG{__DIE__
};
608 $old_WARN = $SIG{__WARN__
};
610 $SIG{__DIE__
} = \
&DEATH
;
611 $SIG{__WARN__
} = \
&TAXES
;
620 Error - Error/exception handling in an OO-ish way
624 Using the "Error" module is B<no longer recommended> due to the black-magical
625 nature of its syntactic sugar, which often tends to break. Its maintainers
626 have stopped actively writing code that uses it, and discourage people
627 from doing so. See the "SEE ALSO" section below for better recommendations.
633 throw Error::Simple( "A simple error");
637 record Error::Simple("A simple error")
641 unlink($file) or throw Error::Simple("$file: $!",$!);
645 die "error!" if $condition;
646 throw Error::Simple "Oops!" if $other_condition;
648 catch Error::IO with {
650 print STDERR "File ", $E->{'-file'}, " had a problem\n";
654 my $general_handler=sub {send_message $E->{-description}};
656 UserException1 => $general_handler,
657 UserException2 => $general_handler
661 print STDERR "Well I don't know what to say\n";
664 close_the_garage_door_already(); # Should be reliable
665 }; # Don't forget the trailing ; or you might be surprised
669 The C<Error> package provides two interfaces. Firstly C<Error> provides
670 a procedural interface to exception handling. Secondly C<Error> is a
671 base class for errors/exceptions that can either be thrown, for
672 subsequent catch, or can simply be recorded.
674 Errors in the class C<Error> should not be thrown directly, but the
675 user should throw errors from a sub-class of C<Error>.
677 =head1 PROCEDURAL INTERFACE
679 C<Error> exports subroutines to perform exception handling. These will
680 be exported if the C<:try> tag is used in the C<use> line.
684 =item try BLOCK CLAUSES
686 C<try> is the main subroutine called by the user. All other subroutines
687 exported are clauses to the try subroutine.
689 The BLOCK will be evaluated and, if no error is throw, try will return
690 the result of the block.
692 C<CLAUSES> are the subroutines below, which describe what to do in the
693 event of an error being thrown within BLOCK.
695 =item catch CLASS with BLOCK
697 This clauses will cause all errors that satisfy C<$err-E<gt>isa(CLASS)>
698 to be caught and handled by evaluating C<BLOCK>.
700 C<BLOCK> will be passed two arguments. The first will be the error
701 being thrown. The second is a reference to a scalar variable. If this
702 variable is set by the catch block then, on return from the catch
703 block, try will continue processing as if the catch block was never
704 found. The error will also be available in C<$@>.
706 To propagate the error the catch block may call C<$err-E<gt>throw>
708 If the scalar reference by the second argument is not set, and the
709 error is not thrown. Then the current try block will return with the
710 result from the catch block.
714 When C<try> is looking for a handler, if an except clause is found
715 C<BLOCK> is evaluated. The return value from this block should be a
716 HASHREF or a list of key-value pairs, where the keys are class names
717 and the values are CODE references for the handler of errors of that
720 =item otherwise BLOCK
722 Catch any error by executing the code in C<BLOCK>
724 When evaluated C<BLOCK> will be passed one argument, which will be the
725 error being processed. The error will also be available in C<$@>.
727 Only one otherwise block may be specified per try block
731 Execute the code in C<BLOCK> either after the code in the try block has
732 successfully completed, or if the try block throws an error then
733 C<BLOCK> will be executed after the handler has completed.
735 If the handler throws an error then the error will be caught, the
736 finally block will be executed and the error will be re-thrown.
738 Only one finally block may be specified per try block
744 L<Moose> exports a keyword called C<with> which clashes with Error's. This
745 example returns a prototype mismatch error:
753 (Thanks to C<maik.hentsche@amd.com> for the report.).
755 =head1 CLASS INTERFACE
759 The C<Error> object is implemented as a HASH. This HASH is initialized
760 with the arguments that are passed to it's constructor. The elements
761 that are used by, or are retrievable by the C<Error> class are listed
762 below, other classes may add to these.
770 If C<-file> or C<-line> are not specified in the constructor arguments
771 then these will be initialized with the file name and line number where
772 the constructor was called from.
774 If the error is associated with an object then the object should be
775 passed as the C<-object> argument. This will allow the C<Error> package
776 to associate the error with the object.
778 The C<Error> package remembers the last error created, and also the
779 last error associated with a package. This could either be the last
780 error created by a sub in that package, or the last error which passed
781 an object blessed into that package as the C<-object> argument.
787 See the Error::Simple documentation.
789 =item throw ( [ ARGS ] )
791 Create a new C<Error> object and throw an error, which will be caught
792 by a surrounding C<try> block, if there is one. Otherwise it will cause
795 C<throw> may also be called on an existing error to re-throw it.
797 =item with ( [ ARGS ] )
799 Create a new C<Error> object and returns it. This is defined for
802 die with Some::Error ( ... );
804 =item record ( [ ARGS ] )
806 Create a new C<Error> object and returns it. This is defined for
809 record Some::Error ( ... )
814 =head2 STATIC METHODS
818 =item prior ( [ PACKAGE ] )
820 Return the last error created, or the last error associated with
823 =item flush ( [ PACKAGE ] )
825 Flush the last error created, or the last error associated with
826 C<PACKAGE>.It is necessary to clear the error stack before exiting the
827 package or uncaught errors generated using C<record> will be reported.
835 =head2 OBJECT METHODS
841 If the variable C<$Error::Debug> was non-zero when the error was
842 created, then C<stacktrace> returns a string created by calling
843 C<Carp::longmess>. If the variable was zero the C<stacktrace> returns
844 the text of the error appended with the filename and line number of
845 where the error was created, providing the text does not end with a
850 The object this error was associated with
854 The file where the constructor of this error was called from
858 The line where the constructor of this error was called from
862 The text of the error
864 =item $err->associate($obj)
866 Associates an error with an object to allow error propagation. I.e:
869 return Error->prior($ber)->associate($ldap);
873 =head2 OVERLOAD METHODS
879 A method that converts the object into a string. This method may simply
880 return the same as the C<text> method, or it may append more
881 information. For example the file name and line number.
883 By default this method returns the C<-text> argument that was passed to
884 the constructor, or the string C<"Died"> if none was given.
888 A method that will return a value that can be associated with the
889 error. For example if an error was created due to the failure of a
890 system call, then this may return the numeric value of C<$!> at the
893 By default this method returns the C<-value> argument that was passed
898 =head1 PRE-DEFINED ERROR CLASSES
902 This class can be used to hold simple error strings and values. It's
903 constructor takes two arguments. The first is a text value, the second
904 is a numeric value. These values are what will be returned by the
907 If the text value ends with C<at file line 1> as $@ strings do, then
908 this information will be used to set the C<-file> and C<-line> arguments
911 This class is used internally if an eval'd block die's with an error
912 that is a plain string. (Unless C<$Error::ObjectifyCallback> is modified)
915 =head1 $Error::ObjectifyCallback
917 This variable holds a reference to a subroutine that converts errors that
918 are plain strings to objects. It is used by Error.pm to convert textual
919 errors to objects, and can be overridden by the user.
921 It accepts a single argument which is a hash reference to named parameters.
922 Currently the only named parameter passed is C<'text'> which is the text
923 of the error, but others may be available in the future.
925 For example the following code will cause Error.pm to throw objects of the
926 class MyError::Bar by default:
928 sub throw_MyError_Bar
931 my $err = MyError::Bar->new();
932 $err->{'MyBarText'} = $args->{'text'};
937 local $Error::ObjectifyCallback = \&throw_MyError_Bar;
939 # Error handling here.
944 =head1 MESSAGE HANDLERS
946 C<Error> also provides handlers to extend the output of the C<warn()> perl
947 function, and to handle the printing of a thrown C<Error> that is not caught
948 or otherwise handled. These are not installed by default, but are requested
949 using the C<:warndie> tag in the C<use> line.
951 use Error qw( :warndie );
953 These new error handlers are installed in C<$SIG{__WARN__}> and
954 C<$SIG{__DIE__}>. If these handlers are already defined when the tag is
955 imported, the old values are stored, and used during the new code. Thus, to
956 arrange for custom handling of warnings and errors, you will need to perform
957 something like the following:
960 $SIG{__WARN__} = sub {
961 print STDERR "My special warning handler: $_[0]"
965 use Error qw( :warndie );
967 Note that setting C<$SIG{__WARN__}> after the C<:warndie> tag has been
968 imported will overwrite the handler that C<Error> provides. If this cannot be
969 avoided, then the tag can be explicitly C<import>ed later
973 $SIG{__WARN__} = ...;
975 import Error qw( :warndie );
979 The C<__DIE__> handler turns messages such as
981 Can't call method "foo" on an undefined value at examples/warndie.pl line 16.
985 Unhandled perl error caught at toplevel:
987 Can't call method "foo" on an undefined value
989 Thrown from: examples/warndie.pl:16
993 main::inner('undef') called at examples/warndie.pl line 20
994 main::outer('undef') called at examples/warndie.pl line 23
1000 See L<Exception::Class> for a different module providing Object-Oriented
1001 exception handling, along with a convenient syntax for declaring hierarchies
1002 for them. It doesn't provide Error's syntactic sugar of C<try { ... }>,
1003 C<catch { ... }>, etc. which may be a good thing or a bad thing based
1004 on what you want. (Because Error's syntactic sugar tends to break.)
1006 L<Error::Exception> aims to combine L<Error> and L<Exception::Class>
1007 "with correct stringification".
1009 L<TryCatch> and L<Try::Tiny> are similar in concept to Error.pm only providing
1010 a syntax that hopefully breaks less.
1014 None, but that does not mean there are not any.
1018 Graham Barr <gbarr@pobox.com>
1020 The code that inspired me to write this was originally written by
1021 Peter Seibel <peter@weblogic.com> and adapted by Jesse Glick
1022 <jglick@sig.bsh.com>.
1024 C<:warndie> handlers added by Paul Evans <leonerd@leonerd.org.uk>
1028 Shlomi Fish, L<http://www.shlomifish.org/> .
1030 =head1 PAST MAINTAINERS
1032 Arun Kumar U <u_arunkumar@yahoo.com>
1036 Copyright (c) 1997-8 Graham Barr. All rights reserved.
1037 This program is free software; you can redistribute it and/or modify it
1038 under the same terms as Perl itself.