Error-Hierarchy

 view release on metacpan or  search on metacpan

lib/Error/Hierarchy/Mixin.pm  view on Meta::CPAN

use 5.008;
use strict;
use warnings;

package Error::Hierarchy::Mixin;
BEGIN {
  $Error::Hierarchy::Mixin::VERSION = '1.103530';
}
# ABSTRACT: Provides often-used exception-related methods
use Error;    # to get $Error::Depth

BEGIN {
    *CORE::GLOBAL::die = sub (@) {

        # Error.pm die()s as well, but we don't want an endless recursion.
        CORE::die(@_) if (caller)[0] eq 'Error' || ref $_[0];
        local $Error::Depth = $Error::Depth + 1;    # skip this level
        throw Error::Hierarchy::Internal::CustomMessage(
            custom_message => join(' ', @_),);
    };
}

# Any class that wants to throw an exception can simply use or inherit from
# this module and call 'throw Error::Whatever' without having to 'require' it
# first. By putting the throw() method in UNIVERSAL:: we catch method calls on
# exception classes that haven't been loaded yet. We load the class, then
# throw the exception.
sub UNIVERSAL::throw {

    # use Data::Dumper; print Dumper \@_; exit if ++(our $cnt) > 5;
    my ($exception_class, %args) = @_;

    # need to modify $Error::Depth (see Error.pm) to make certain parts
    # of the call stack invisible to caller()
    # +1 to make UNIVERSAL::throw() invisible
    # in case it wasn't loaded; to make sure $Error::Depth isn't undef
    require Error;
    local $Error::Depth = $Error::Depth + 1;
    eval "require $exception_class";
    CORE::die($@) if $@;
    $exception_class->throw(%args);
}

# Similar reasoning for record().
sub UNIVERSAL::record {
    my ($exception_class, %args) = @_;

    # need to modify $Error::Depth (see Error.pm) to make certain parts
    # of the call stack invisible to caller()
    # +1 to make UNIVERSAL::record() invisible
    # in case it wasn't loaded; to make sure $Error::Depth isn't undef
    require Error;
    local $Error::Depth = $Error::Depth + 1;
    eval "require $exception_class";
    CORE::die $@ if $@;
    $exception_class->record(%args);
}
1;


__END__
=pod

=head1 NAME

Error::Hierarchy::Mixin - Provides often-used exception-related methods

=head1 VERSION

version 1.103530

=head1 SYNOPSIS

  package MyClass;
  use Error::Hierarchy::Mixin;



( run in 0.468 second using v1.01-cache-2.11-cpan-5511b514fd6 )