# # $Id: //depot/prod/DOT/dev/test/nate/lib/NATE/Error.pm#1 $ # # ********************************************************* # This file has been modified from its original version. # Changed the package name from Error to NATE::Error. # Modified Version 0.17008 in Dec 2009 # ********************************************************* # # Error.pm # # Copyright (c) 1997-8 Graham Barr . All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # # Based on my original Error.pm, and Exceptions.pm by Peter Seibel # and adapted by Jesse Glick . # # but modified ***significantly*** # ## @pod here package NATE::Error; use v5.14; use strict; use vars qw($VERSION); use NATE::BaseException; $VERSION = "0.17008"; use overload ( '""' => 'stringify', '0+' => 'value', 'bool' => sub { return 1; }, 'fallback' => 1 ); $NATE::Error::Depth = 0; # Depth to pass to caller() $NATE::Error::Debug = 0; # Generate verbose stack traces @NATE::Error::STACK = (); # Clause stack for try $NATE::Error::THROWN = undef; # last error thrown, a workaround until die $ref works my $LAST; # Last error created my %ERROR; # Last error associated with package sub _throw_BaseException { my $args = shift; return NATE::BaseException->new($args->{'text'}); } $NATE::Error::ObjectifyCallback = \&_throw_BaseException; # Exported subs are defined in NATE::Error::subs. use Scalar::Util (); sub import { shift; my @tags = @_; local $Exporter::ExportLevel = $Exporter::ExportLevel + 1; @tags = grep { if( $_ eq ':warndie' ) { NATE::Error::WarnDie->import(); 0; } else { 1; } } @tags; NATE::Error::subs->import(@tags); } # I really want to use last for the name of this method, but it is a keyword # which prevents the syntax last Error. sub prior { shift; # ignore return $LAST unless @_; my $pkg = shift; return exists $ERROR{$pkg} ? $ERROR{$pkg} : undef unless ref($pkg); my $obj = $pkg; my $err = undef; if($obj->isa('HASH')) { $err = $obj->{'__Error__'} if exists $obj->{'__Error__'}; } elsif($obj->isa('GLOB')) { $err = ${*$obj}{'__Error__'} if exists ${*$obj}{'__Error__'}; } $err; } sub flush { shift; #ignore unless (@_) { $LAST = undef; return; } my $pkg = shift; return unless ref($pkg); undef $ERROR{$pkg} if defined $ERROR{$pkg}; } # Returns as much information as possible about the location of the error. # The -stacktrace element exists only if $NATE::Error::DEBUG # is set when the error is created. sub stacktrace { my $self = shift; return $self->{'-stacktrace'} if exists $self->{'-stacktrace'}; my $text = exists $self->{'-text'} ? $self->{'-text'} : "Died"; $text .= sprintf(" at %s line %d.\n", $self->file, $self->line) unless($text =~ /\n$/s); $text; } sub associate { my $err = shift; my $obj = shift; return unless ref($obj); if($obj->isa('HASH')) { $obj->{'__Error__'} = $err; } elsif($obj->isa('GLOB')) { ${*$obj}{'__Error__'} = $err; } $obj = ref($obj); $ERROR{ ref($obj) } = $err; return; } sub new { my $self = shift; my($pkg,$file,$line) = caller($NATE::Error::Depth); my $err = bless { '-package' => $pkg, '-file' => $file, '-line' => $line, @_ }, $self; $err->associate($err->{'-object'}) if(exists $err->{'-object'}); # To create a stacktrace always would be very inefficient, so # we do it only if $NATE::Error::Debug is set. if($NATE::Error::Debug) { require Carp; local $Carp::CarpLevel = $NATE::Error::Depth; my $text = defined($err->{'-text'}) ? $err->{'-text'} : "Error"; my $trace = Carp::longmess($text); # Remove try calls from the trace $trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+NATE::Error::subs::try[^\n]+(?=\n)//sog; $trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+NATE::Error::subs::run_clauses[^\n]+\n\s+NATE::Error::subs::try[^\n]+(?=\n)//sog; $err->{'-stacktrace'} = $trace } $@ = $LAST = $ERROR{$pkg} = $err; } # Throws an error. This contains the following code: sub throw { my $self = shift; local $NATE::Error::Depth = $NATE::Error::Depth + 1; # If we do not rethrow, then create the object to throw. $self = $self->new(@_) unless ref($self); die $NATE::Error::THROWN = $self; } # Using "die with Error" instead of "die new Error" makes the following code more readable: # # die with Error( ... ); sub with { my $self = shift; local $NATE::Error::Depth = $NATE::Error::Depth + 1; $self->new(@_); } # Using "die with Error" instead of "die new Error" makes the following code more readable: # # record Error( ... ) and return; sub record { my $self = shift; local $NATE::Error::Depth = $NATE::Error::Depth + 1; $self->new(@_); } # catch clause for # # try { ... } catch CLASS with { ... } sub catch { my $pkg = shift; my $code = shift; my $clauses = shift || {}; my $catch = $clauses->{'catch'} ||= []; unshift @$catch, $pkg, $code; $clauses; } # Object query and set methods # The query methods have the same name as the object attribute # The set methods are named "set_" # The attributes for which this is supported are: object, file, line and text BEGIN { # Symbolic references are disabled by default, so enable them no strict 'refs'; foreach my $object_attribute (qw(object file line text)) { *{$object_attribute} = sub { my $self = shift; exists $self->{"-$object_attribute"} ? $self->{"-$object_attribute"} : undef; }; *{"set_$object_attribute"} = sub { my $self = shift; $self->{"-$object_attribute"} = shift; }; } use strict 'refs'; } # overload methods sub stringify { my $self = shift; defined $self->{'-text'} ? $self->{'-text'} : "Died"; } sub value { my $self = shift; exists $self->{'-value'} ? $self->{'-value'} : undef; } # This storable hook just exists for the side effect that Storable # will do 'require MyException' on demand when thawing a MyException # class derived from this class. This makes sure derived class # objects will be usable if they are frozen, sent to other process, # and thawed. sub STORABLE_freeze { my ( $self, $cloning ) = @_; return if $cloning; # Regular default serialization my (%data) = (%$self); return ( "", \%data ); } sub STORABLE_thaw { my ( $self, $cloning, $dummy, $data ) = @_; %$self = %$data; } package NATE::Error::Simple; @NATE::Error::Simple::ISA = qw(NATE::Error); sub new { my $self = shift; my $text = "" . shift; my $value = shift; my(@args) = (); local $NATE::Error::Depth = $NATE::Error::Depth + 1; @args = ( -file => $1, -line => $2) if($text =~ s/\s+at\s+(\S+)\s+line\s+(\d+)(?:,\s*<[^>]*>\s+line\s+\d+)?\.?\n?$//s); push(@args, '-value', 0 + $value) if defined($value); $self->SUPER::new(-text => $text, @args); } sub stringify { my $self = shift; my $text = $self->SUPER::stringify; $text .= sprintf(" at %s line %d.\n", $self->file, $self->line) unless($text =~ /\n$/s); $text; } ########################################################################## ########################################################################## # Inspired by code from Jesse Glick and # Peter Seibel . package NATE::Error::subs; use Exporter (); use vars qw(@EXPORT_OK @ISA %EXPORT_TAGS); @EXPORT_OK = qw(try with finally except otherwise); %EXPORT_TAGS = (try => \@EXPORT_OK); @ISA = qw(Exporter); sub run_clauses ($$$\@) { my($clauses,$err,$wantarray,$result) = @_; my $code = undef; $err = $NATE::Error::ObjectifyCallback->({'text' =>$err}) unless ref($err); CATCH: { # catch my $catch; if(defined($catch = $clauses->{'catch'})) { my $i = 0; CATCHLOOP: for( ; $i < @$catch ; $i += 2) { my $pkg = $catch->[$i]; unless(defined $pkg) { #except splice(@$catch,$i,2,$catch->[$i+1]->()); $i -= 2; next CATCHLOOP; } elsif(Scalar::Util::blessed($err) && $err->isa($pkg)) { $code = $catch->[$i+1]; while(1) { my $more = 0; local($NATE::Error::THROWN, $@); my $ok = eval { $@ = $err; if($wantarray) { @{$result} = $code->($err,\$more); } elsif(defined($wantarray)) { @{$result} = (); $result->[0] = $code->($err,\$more); } else { $code->($err,\$more); } 1; }; if( $ok ) { next CATCHLOOP if $more; undef $err; } else { $err = defined($NATE::Error::THROWN) ? $NATE::Error::THROWN : $@; $err = $NATE::Error::ObjectifyCallback->({'text' =>$err}) unless ref($err); } last CATCH; }; } } } # otherwise my $owise; if(defined($owise = $clauses->{'otherwise'})) { my $code = $clauses->{'otherwise'}; my $more = 0; local($NATE::Error::THROWN, $@); my $ok = eval { $@ = $err; if($wantarray) { @{$result} = $code->($err,\$more); } elsif(defined($wantarray)) { @{$result} = (); $result->[0] = $code->($err,\$more); } else { $code->($err,\$more); } 1; }; if( $ok ) { undef $err; } else { $err = defined($NATE::Error::THROWN) ? $NATE::Error::THROWN : $@; $err = $NATE::Error::ObjectifyCallback->({'text' =>$err}) unless ref($err); } } } $err; } sub try (&;$) { my $try = shift; my $clauses = @_ ? shift : {}; my $ok = 0; my $err = undef; my @result = (); unshift @NATE::Error::STACK, $clauses; my $wantarray = wantarray(); do { local $NATE::Error::THROWN = undef; local $@ = undef; $ok = eval { if($wantarray) { @result = $try->(); } elsif(defined $wantarray) { $result[0] = $try->(); } else { $try->(); } 1; }; $err = defined($NATE::Error::THROWN) ? $NATE::Error::THROWN : $@ unless $ok; }; shift @NATE::Error::STACK; $err = run_clauses($clauses,$err,wantarray,@result) unless($ok); $clauses->{'finally'}->() if(defined($clauses->{'finally'})); if (defined($err)) { if (Scalar::Util::blessed($err) && $err->can('throw')) { throw $err; } else { die $err; } } wantarray ? @result : $result[0]; } # Each clause adds a sub to the list of clauses. The finally clause is # always the last, and the otherwise clause is always added just before # the finally clause. # # All clauses, except the finally clause, add a sub which takes one argument. # This argument is the error being thrown. The sub will return a code ref # if that clause can handle that error; otherwise, undef is returned. # # The otherwise clause adds a sub which unconditionally returns the users # code reference. This is why it is forced to be last. # # The catch clause is defined in NATE::Error.pm, as the syntax causes it to # be called as a method. sub with (&;$) { @_ } sub finally (&) { my $code = shift; my $clauses = { 'finally' => $code }; $clauses; } # The except clause is a block which returns a hashref or a list of # key-value pairs, where the keys are the classes and the values are subs. sub except (&;$) { my $code = shift; my $clauses = shift || {}; my $catch = $clauses->{'catch'} ||= []; my $sub = sub { my $ref; my(@array) = $code->($_[0]); if(@array == 1 && ref($array[0])) { $ref = $array[0]; $ref = [ %$ref ] if(UNIVERSAL::isa($ref,'HASH')); } else { $ref = \@array; } @$ref }; unshift @{$catch}, undef, $sub; $clauses; } sub otherwise (&;$) { my $code = shift; my $clauses = shift || {}; if(exists $clauses->{'otherwise'}) { require Carp; Carp::croak("Multiple otherwise clauses"); } $clauses->{'otherwise'} = $code; $clauses; } 1; package NATE::Error::WarnDie; sub gen_callstack($) { my ( $start ) = @_; require Carp; local $Carp::CarpLevel = $start; my $trace = Carp::longmess(""); # Remove try calls from the trace. $trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+NATE::Error::subs::try[^\n]+(?=\n)//sog; $trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+NATE::Error::subs::run_clauses[^\n]+\n\s+NATE::Error::subs::try[^\n]+(?=\n)//sog; my @callstack = split( m/\n/, $trace ); return @callstack; } my $old_DIE; my $old_WARN; sub DEATH { my ( $e ) = @_; local $SIG{__DIE__} = $old_DIE if( defined $old_DIE ); die @_ if $^S; my ( $etype, $message, $location, @callstack ); if ( ref($e) && $e->isa( "NATE::Error" ) ) { $etype = "exception of type " . ref( $e ); $message = $e->text; $location = $e->file . ":" . $e->line; @callstack = split( m/\n/, $e->stacktrace ); } else { # Do not apply subsequent layer of message formatting. die $e if( $e =~ m/^\nUnhandled perl error caught at toplevel:\n\n/ ); $etype = "perl error"; my $stackdepth = 0; while( caller( $stackdepth ) =~ m/^NATE::Error(?:$|::)/ ) { $stackdepth++ } @callstack = gen_callstack( $stackdepth + 1 ); $message = "$e"; chomp $message; if ( $message =~ s/ at (.*?) line (\d+)\.$// ) { $location = $1 . ":" . $2; } else { my @caller = caller( $stackdepth ); $location = $caller[1] . ":" . $caller[2]; } } shift @callstack; # Do it this way in case there are no elements; we do not print a spurious \n. my $callstack = join( "", map { "$_\n"} @callstack ); die "\nUnhandled $etype caught at toplevel:\n\n $message\n\nThrown from: $location\n\nFull stack trace:\n\n$callstack\n"; } sub TAXES { my ( $message ) = @_; local $SIG{__WARN__} = $old_WARN if( defined $old_WARN ); $message =~ s/ at .*? line \d+\.$//; chomp $message; my @callstack = gen_callstack( 1 ); my $location = shift @callstack; # $location already starts in a leading space. $message .= $location; # Do it this way in case there are no elements; we do not print a spurious \n. my $callstack = join( "", map { "$_\n"} @callstack ); warn "$message:\n$callstack"; } sub import { $old_DIE = $SIG{__DIE__}; $old_WARN = $SIG{__WARN__}; $SIG{__DIE__} = \&DEATH; $SIG{__WARN__} = \&TAXES; } 1; __END__ =head1 NAME NATE::Error - Error or Exception Handling in an OO-ish Way =head1 SYNOPSIS use NATE::Error qw(:try); throw NATE::Error::Simple( "A simple error"); sub xyz { ... record NATE::Error::Simple("A simple error") and return; } unlink($file) or throw NATE::Error::Simple("$file: $!",$!); try { do_some_stuff(); die "error!" if $condition; throw NATE::Error::Simple "Oops!" if $other_condition; } catch NATE::Error::IO with { my $E = shift; print STDERR "File ", $E->{'-file'}, " had a problem\n"; } except { my $E = shift; my $general_handler=sub {send_message $E->{-description}}; return { UserException1 => $general_handler, UserException2 => $general_handler }; } otherwise { print STDERR "Well I don't know what to say\n"; } finally { close_the_garage_door_already(); # Should be reliable }; # Don't forget the trailing ; or you might be surprised =head1 DESCRIPTION The C package provides the following interfaces: =over 4 =item * C provides a procedural interface to exception handling. =item * C is a base class for errors or exceptions that can either be thrown for subsequent catch or can be recorded. =back Errors in the class C should not be thrown directly, but the user must throw errors from a sub-class of C. =head1 PROCEDURAL INTERFACE C exports subroutines to perform exception handling. The subroutines are exported if the C<:try> tag is used in the C line. =over 4 =item try BLOCK CLAUSES The subroutine C is the main subroutine called by the user. All other subroutines exported are clauses to the try subroutine. The BLOCK is evaluated and if no error is thrown, C returns the result of the block. The C subroutines below describe what is to be done in the event of an error being thrown within BLOCK. =item catch CLASS with BLOCK This clause causes all errors that satisfy C<$err-Eisa(CLASS)> to be caught and handled by evaluating C. Two arguments are passed to C. The first argument passed is the error being thrown. The second argument is a reference to a scalar variable. If this variable is set by the catch block, then on returning from the catch block, C continues processing as if the catch block was never found. The error is also available in C<$@>. To propagate the error, the catch block might call C<$err-Ethrow>. If the scalar reference by the second argument is not set, and the error is not thrown, then the current C block returns with the result from the block. =item except BLOCK If an clause is found while C is looking for a handler, C is evaluated. The return value from this block must be a HASHREF or a list of key-value pairs, where the keys are class names and the values are CODE references for the handler of errors of that type. =item otherwise BLOCK This clause catches any error by executing the code in C. When evaluated, C is passed one argument, which is the error being processed. The error is also available in C<$@>. Only one C block can be specified per C block. =item finally BLOCK The C block is executed if the handler throws an error. Execute the code in C either after the code in the try block has successfully completed or if the try block throws an error, then C is executed after the handler has completed. If the handler throws an error, the error is caught, the C block is executed, and the error is re-thrown. Only one C block can be specified per C block. =back =head1 CLASS INTERFACE =head2 Constructors The C object is implemented as a HASH. This HASH is initialized with the arguments that are passed to its constructor. The elements that are used by the C class, or can be retrieved by the class are listed below. Other classes might add to the following: -file -line -text -value -object If C<-file> or C<-line> are not specified in the constructor arguments, then they will be initialized with the file name and line number from where the constructor was called. If the error is associated with an object, the object must be passed as the C<-object> argument. This will allow the C package to associate the error with the object. The C package remembers the last error created, and also the last error associated with a package. This can either be the last error created by a sub in that package, or the last error which passes an object given to that package as the C<-object> argument. The arguments are the following: =over 4 =item throw ( [ ARGS ] ) This argument creates a new C object and throws an error, which is caught by a surrounding C block, if there is one. Otherwise, it causes the program to exit. C might also be called on an existing error to re-throw it. =item with ( [ ARGS ] ) This argument creates a new C object and returns it. This is defined for syntactic sugar. For example, die with Some::Error ( ... ); =item record ( [ ARGS ] ) This argument creates a new C object and returns it. This is defined for syntactic sugar. For example, record Some::Error ( ... ) and return; =back =head2 Static Methods =over 4 =item prior ( [ PACKAGE ] ) This method returns the last error created, or the last error associated with C. =item flush ( [ PACKAGE ] ) This method flushes the last error created, or the last error associated with C. It is necessary to clear the error stack before exiting the package, or uncaught errors generated using C will be reported. $Error->flush; =cut =back =head2 Object Methods =over 4 =item stacktrace If the variable C<$NATE::Error::Debug> was non-zero when the error was created, then C returns a string created by calling C. If the variable was zero, the C returns the text of the error appended with the filename and the line number where the error was created, provided the text does not end with a newline. =item object This is the object with which the error is associated. =item file This is the file from where the constructor of the error was called. =item line This is the line from where the constructor of the error was called. =item text This is the text of the error. =item $err->associate($obj) This method associates an error with an object to allow error propagation. For example, $ber->encode(...) or return Error->prior($ber)->associate($ldap); =back =head2 Overload Methods =over 4 =item stringify This method converts the object into a string. This method simply returns the same as the C method, or it might append more information. For example, the file name and line number. By default, this method returns the C<-text> argument that was passed to the constructor, or the string C<"Died">, if none was given. =item value This method returns a value that can be associated with the error. For example, if an error was created due to the failure of a system call, this method then returns the numeric value of C<$!>. By default, this method returns the C<-value> argument that was passed to the constructor. =back =head1 PRE-DEFINED ERROR CLASSES =head2 NATE::Error::Simple This class can be used to hold simple error strings and values. The constructor of this class takes two arguments; the first is a text value, and the second is a numeric value. These values are the values that are returned by the overload methods. If the text value ends with C as $@ strings do, then this infomation will be used to set the C<-file> and C<-line> arguments of the error object. This class is used internally if an eval'd block dies with an error that is a plain string, unless C<$NATE::Error::ObjectifyCallback> is modified. =head1 $NATE::Error::ObjectifyCallback This variable holds a reference to a subroutine that converts errors, which are plain strings to objects. It is used by NATE::Error.pm to convert textual errors to objects, and can be overriden by the user. It accepts a single argument, which is a hash reference to named parameters. Currently, the only named parameter passed is C<'text'>, which is the text of the error; others might be available in the future. For example, the following code causes NATE::Error.pm to throw objects of the class MyError::Bar by default: sub throw_MyError_Bar { my $args = shift; my $err = MyError::Bar->new(); $err->{'MyBarText'} = $args->{'text'}; return $err; } { local $NATE::Error::ObjectifyCallback = \&throw_MyError_Bar; # Error handling here. } =cut =head1 MESSAGE HANDLERS C also provides handlers to extend the output of the C Perl function, and to handle the printing of a thrown C that is not caught, or otherwise handled. These are not installed by default, but are requested using the C<:warndie> tag in the C line. use NATE::Error qw( :warndie ); These new error handlers are installed in C<$SIG{__WARN__}> and C<$SIG{__DIE__}>. If these handlers are already defined when the tag is imported, the old values are stored and used during the new code. Therefore, to arrange for custom handling of warnings and errors, you will need to perform the following: BEGIN { $SIG{__WARN__} = sub { print STDERR "My special warning handler: $_[0]" }; } use NATE::Error qw( :warndie ); Note that setting C<$SIG{__WARN__}> after the C<:warndie> tag has been imported will overwrite the handler that C provides. If this cannot be avoided, the tag can be explicitly Ced later. use NATE::Error; $SIG{__WARN__} = ...; import NATE::Error qw( :warndie ); =head2 Example The C<__DIE__> handler turns the following message: Can't call method "foo" on an undefined value at examples/warndie.pl line 16. into the following nessages: Unhandled perl error caught at toplevel: Can't call method "foo" on an undefined value Thrown from: examples/warndie.pl:16 Full stack trace: main::inner('undef') called at examples/warndie.pl line 20 main::outer('undef') called at examples/warndie.pl line 23 =cut =head1 KNOWN BUGS There are no bugs that are known, but that does not mean there are no bugs. =head1 AUTHORS Graham Barr The code that inspired me to write this was originally written by Peter Seibel and adapted by Jesse Glick . C<:warndie> handlers added by Paul Evans . =head1 MAINTAINER Shlomi Fish =head1 PAST MAINTAINERS Arun Kumar U =head1 COPYRIGHT Copyright (c) 1997-8 Graham Barr. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut