File Coverage

blib/lib/Exception/Class/TryCatch.pm
Criterion Covered Total %
statement 31 31 100.0
branch 21 22 95.4
condition 2 3 66.6
subroutine 6 6 100.0
pod 2 2 100.0
total 62 64 96.8


line stmt bran cond sub pod time code
1 1     1   32417 use strict;
  1         3  
  1         61  
2 1     1   6 use warnings;
  1         3  
  1         118  
3              
4             package Exception::Class::TryCatch;
5             # ABSTRACT: Syntactic try/catch sugar for use with Exception::Class
6             our $VERSION = '1.13'; # VERSION
7              
8             our @ISA = qw (Exporter);
9             our @EXPORT = qw ( catch try );
10             our @EXPORT_OK = qw ( caught );
11              
12 1     1   1716 use Exception::Class;
  1         23722  
  1         8  
13 1     1   59 use Exporter ();
  1         3  
  1         330  
14              
15             my @error_stack;
16              
17             #--------------------------------------------------------------------------#
18             # catch()
19             #--------------------------------------------------------------------------#
20              
21             sub catch(;$$) { ## no critic
22 30     30 1 9440 my $e;
23 30 100       76 my $err = @error_stack ? pop @error_stack : $@;
24 30 100       107 if ( UNIVERSAL::isa( $err, 'Exception::Class::Base' ) ) {
    100          
25 15         19 $e = $err;
26             }
27             elsif ( $err eq '' ) {
28 12         18 $e = undef;
29             }
30             else {
31             # use error message or hope something stringifies
32 3         15 $e = Exception::Class::Base->new("$err");
33             }
34 30 100       768 unless ( ref( $_[0] ) eq 'ARRAY' ) {
35 27         36 $_[0] = $e;
36 27         91 shift;
37             }
38 30 100       82 if ($e) {
39 18 100 66     119 if ( defined( $_[0] ) and ref( $_[0] ) eq 'ARRAY' ) {
40 2 50       4 $e->rethrow() unless grep { $e->isa($_) } @{ $_[0] };
  2         25  
  2         4  
41             }
42             }
43 28 100       100 return wantarray ? ( $e ? ($e) : () ) : $e;
    100          
44             }
45              
46             *caught = \&catch;
47              
48             #--------------------------------------------------------------------------#
49             # try()
50             #--------------------------------------------------------------------------#
51              
52             sub try($) { ## no critic
53 19     19 1 8279 my $v = shift;
54 19         29 push @error_stack, $@;
55 19 100       48 return ref($v) eq 'ARRAY' ? @$v : $v if wantarray;
    100          
56 17         33 return $v;
57             }
58              
59             1;
60              
61             __END__