Error subs
Other packages in the module: Error Error::Simple
SummaryIncluded librariesPackage variablesSynopsisDescriptionGeneral documentationMethods
Toolbar
WebCvsRaw content
Summary
Error - Error/exception handling in an OO-ish way
Package variables
Globals (from "use vars" definitions)
%EXPORT_TAGS = (try =>\@ EXPORT_OK)
@EXPORT_OK
Included modules
Exporter ( )
Inherit
Exporter
Synopsis
    use Error qw(:try);
throw Error::Simple( "A simple error"); sub xyz { ... record Error::Simple("A simple error") and return; } unlink($file) or throw Error::Simple("$file: $!",$!); try { do_some_stuff(); die "error!" if $condition; throw Error::Simple -text => "Oops!" if $other_condition; } catch 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
Description
The Error package provides two interfaces. Firstly Error provides
a procedural interface to exception handling. Secondly Error is a
base class for errors/exceptions that can either be thrown, for
subsequent catch, or can simply be recorded.
Errors in the class Error should not be thrown directly, but the
user should throw errors from a sub-class of Error.
Methods
except
No description
Code
finally
No description
Code
otherwise
No description
Code
run_clauses
No description
Code
try
No description
Code
with
No description
Code
Methods description
None available.
Methods code
exceptdescriptionprevnextTop
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, $code;

    $clauses;
}
finallydescriptionprevnextTop
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.
}
otherwisedescriptionprevnextTop
sub otherwise {
(&;$) {    my $code = shift;
    my $clauses = shift || {};

    if(exists $clauses->{'otherwise'}) {
	require Carp;
	Carp::croak("Multiple otherwise clauses");
    }

    $clauses->{'otherwise'} = $code;

    $clauses;
}

1;
__END__
}
run_clausesdescriptionprevnextTop
sub run_clauses {
($$$\@) {    my($clauses,$err,$wantarray,$result) = @_;
    my $code = undef;

    $err = new Error::Simple($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 CATCH; } elsif($err->isa($pkg)) { $code = $catch->[$i+1]; while(1) { my $more = 0; local($Error::THROWN); my $ok = eval { 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($Error::THROWN) ? $Error::THROWN : $@; $err = new Error::Simple($err) unless ref($err); } last CATCH; }; } } } # otherwise
my $owise; if(defined($owise = $clauses->{'otherwise'})) { my $code = $clauses->{'otherwise'}; my $more = 0; my $ok = eval { 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($Error::THROWN) ? $Error::THROWN : $@; $err = new Error::Simple($err) unless ref($err); } } } $err;
}
trydescriptionprevnextTop
sub try {
(&;$) {    my $try = shift;
    my $clauses = @_ ? shift : {};
    my $ok = 0;
    my $err = undef;
    my @result = ();

    unshift @Error::STACK, $clauses;

    do {
	local $Error::THROWN = undef;

	$ok = eval {
	    if(wantarray) {
		@result = $try->();
	    }
	    elsif(defined wantarray) {
		$result[0] = $try->();
	    }
	    else {
		$try->();
	    }
	    1;
	};

	$err = defined($Error::THROWN) ? $Error::THROWN : $@
	    unless $ok;
    };

    shift @Error::STACK;

    $err = run_clauses($clauses,$err,wantarray,@result)
	unless($ok);

    $clauses->{'finally'}->()
	if(defined($clauses->{'finally'}));

    throw $err if defined($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 will be 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 Error.pm, as the syntax causes it to
# be called as a method
}
withdescriptionprevnextTop
sub with {
(&;$) {    @_
}
General documentation
PROCEDURAL INTERFACETop
Error exports subroutines to perform exception handling. These will
be exported if the :try tag is used in the use line.
    try BLOCK CLAUSES
try is the main subroutine called by the user. All other subroutines
exported are clauses to the try subroutine.
    The BLOCK will be evaluated and, if no error is throw, try will return
the result of the block.
CLAUSES are the subroutines below, which describe what to do in the
event of an error being thrown within BLOCK.
    catch CLASS with BLOCK
    This clauses will cause all errors that satisfy $err-E<gt>isa(CLASS)
to be caught and handled by evaluating BLOCK.
BLOCK will be passed two arguments. The first will be the error
being thrown. The second is a reference to a scalar variable. If this
variable is set by the catch block then, on return from the catch
block, try will continue processing as if the catch block was never
found.
    To propagate the error the catch block may call $err-E<gt>throw
    If the scalar reference by the second argument is not set, and the
error is not thrown. Then the current try block will return with the
result from the catch block.
    except BLOCK
    When try is looking for a handler, if an except clause is found
BLOCK is evaluated. The return value from this block should 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.
    otherwise BLOCK
    Catch any error by executing the code in BLOCK
    When evaluated BLOCK will be passed one argument, which will be the
error being processed.
    Only one otherwise block may be specified per try block
    finally BLOCK
    Execute the code in BLOCK either after the code in the try block has
successfully completed, or if the try block throws an error then
BLOCK will be executed after the handler has completed.
    If the handler throws an error then the error will be caught, the
finally block will be executed and the error will be re-thrown.
    Only one finally block may be specified per try block
CLASS INTERFACETop
CONSTRUCTORSTop
The Error object is implemented as a HASH. This HASH is initialized
with the arguments that are passed to it's constructor. The elements
that are used by, or are retrievable by the Error class are listed
below, other classes may add to these.
	-file
-line
-text
-value
-object
If -file or -line are not specified in the constructor arguments
then these will be initialized with the file name and line number where
the constructor was called from.
If the error is associated with an object then the object should be
passed as the -object argument. This will allow the Error package
to associate the error with the object.
The Error package remembers the last error created, and also the
last error associated with a package. This could either be the last
error created by a sub in that package, or the last error which passed
an object blessed into that package as the -object argument.
    throw ( [ ARGS ] )
    Create a new Error object and throw an error, which will be caught
by a surrounding try block, if there is one. Otherwise it will cause
the program to exit.
throw may also be called on an existing error to re-throw it.
    with ( [ ARGS ] )
    Create a new Error object and returns it. This is defined for
syntactic sugar, eg
    die with Some::Error ( ... );
    record ( [ ARGS ] )
    Create a new Error object and returns it. This is defined for
syntactic sugar, eg
    record Some::Error ( ... )
and return;
STATIC METHODSTop
    prior ( [ PACKAGE ] )
    Return the last error created, or the last error associated with
PACKAGE
OBJECT METHODSTop
    stacktrace
    If the variable $Error::Debug was non-zero when the error was
created, then stacktrace returns a string created by calling
Carp::longmess. If the variable was zero the stacktrace returns
the text of the error appended with the filename and line number of
where the error was created, providing the text does not end with a
newline.
    object
    The object this error was associated with
    file
    The file where the constructor of this error was called from
    line
    The line where the constructor of this error was called from
    text
    The text of the error
OVERLOAD METHODSTop
    stringify
    A method that converts the object into a string. This method may simply
return the same as the text method, or it may append more
information. For example the file name and line number.
    By default this method returns the -text argument that was passed to
the constructor, or the string "Died" if none was given.
    value
    A method that will return a value that can be associated with the
error. For example if an error was created due to the failure of a
system call, then this may return the numeric value of $! at the
time.
    By default this method returns the -value argument that was passed
to the constructor.
PRE-DEFINED ERROR CLASSESTop
    Error::Simple
    This class can be used to hold simple error strings and values. It's
constructor takes two arguments. The first is a text value, the second
is a numeric value. These values are what will be returned by the
overload methods.
    If the text value ends with at file line 1 as $@ strings do, then
this infomation will be used to set the -file and -line arguments
of the error object.
    This class is used internally if an eval'd block die's with an error
that is a plain string.
KNOWN BUGSTop
None, but that does not mean there are not any.
AUTHORSTop
Graham Barr <gbarr@pobox.com>
The code that inspired me to write this was originally written by
Peter Seibel <peter@weblogic.com> and adapted by Jesse Glick
<jglick@sig.bsh.com>.