Mojo/Exception.pm

filter: Statementstmt 100% 110 / 110 Branchbran 92.8% 52 / 56 Conditioncond 78.9% 30 / 38 MC/DCmcdc 33.3% 6 / 18 Subroutinesub 100% 20 / 20 Podpod 100% 7 / 7 totaltotal 90.3% 225 / 249 CC 51 SCAR 22.5
CC
51
Cov
94%
check
19.3
_context
10.1
to_string
9.0
CRAP 9.5
« Mojo/Content.pm ↑ Summary Mojo/Transaction.pm »
1 package Mojo::Exception;
2 36 ▶use Mojo::Base -base;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 36 ▶use overload bool => sub {1}, '""' => sub { shift->to_string }, fallback => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
4  
5 36 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 36 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 36 ▶use Mojo::Util qw(decode);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 36 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 192 ▶has [qw(frames line lines_after lines_before)] => sub { [] };
Subroutine __ANON__: called CC=1 SCAR=0.0
11 36 has message => 'Exception!';
12 150 ▶has verbose => sub { $ENV{MOJO_EXCEPTION_VERBOSE} };
Subroutine __ANON__: called CC=1 SCAR=0.0
13  
14 36 our @EXPORT_OK = qw(check raise);
15  
16 15 ▶sub check {
Subroutine check: called CC=19 SCAR=29.6
Pod documented
17 15 my ($err, $spec) = @_;
18 15 ▶ return undef unless $err;
Branch: 1 branch
BranchTrueFalseTotal
unless $err 2 13 15
19  
20 13 ▶ croak "Array reference of pattern/handler pairs required to dispatch exceptions"
Branch: 1 branch
BranchTrueFalseTotal
if ref $spec ne "ARRAY" or @$spec % 2 2 11 13
Condition100%3/3
ref $spec ne "ARRAY" or @$spec % 2
l!l&&r!l&&!r
1111
MC/DC100%2/2
ref $spec ne "ARRAY" or @$spec % 2
ref $spec ne "ARRAY" @$spec % 2
Truth table100%3/3
A or B
A= ref $spec ne "ARRAY"B= @$spec % 2
ABresult
1X1
011
000
21 if ref $spec ne 'ARRAY' || @$spec % 2;
22  
23 11 my ($default, $handler);
24 11 my ($is_obj, $str) = (!!blessed($err), "$err");
25 11 ▶CHECK: for (my $i = 0; $i < @$spec; $i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$spec) 20 3 23
26 20 my ($checks, $cb) = @{$spec}[$i, $i + 1];
27  
28 20 ▶ ($default = $cb) and next if $checks eq 'default';
Branch: 1 branch
BranchTrueFalseTotal
if $checks eq "default" 4 16 20
Condition60%3/5
$checks eq 'default' && (($default = $cb) && (next))
!ll&&!rl&&r
1640
$default = $cb and next
!ll
04
MC/DC0%0/2
$checks eq 'default' && (($default = $cb) && (next))
$checks eq 'default' $default = $cb
Truth table33%1/3
A && B
A= $checks eq 'default'B= $default = $cb
ABresult
0X0
100
111
29  
30 16 ▶ for my $c (ref $checks eq 'ARRAY' ? @$checks : $checks) {
Branch: 1 branch
BranchTrueFalseTotal
ref $checks eq 'ARRAY' ? : 3 13 16
31 18 my $is_re = !!ref $c;
32 18 ▶ ($handler = $cb) and last CHECK if $is_obj && !$is_re && $err->isa($c);
Branch: 1 branch
BranchTrueFalseTotal
if $is_obj and not $is_re and $err->isa($c) 5 13 18
Condition81%9/11
$is_obj && !$is_re && $err->isa($c) && (($handler = $cb) && (last CHECK))
!ll&&!rl&&r
1350
$is_obj and not $is_re and $err->isa($c)
!ll&&!rl&&r
765
$is_obj and not $is_re
!ll&&!rl&&r
5211
$handler = $cb and last CHECK
!ll
05
MC/DC0%0/4
$is_obj && !$is_re && $err->isa($c) && (($handler = $cb) && (last CHECK))
$is_obj not $is_re $err->isa($c) $handler = $cb
Truth table60%3/5
A and not(B) and C && D
A= $is_objB= not $is_reC= $err->isa($c)D= $handler = $cb
ABCDresult
0XXX0
10XX0
110X0
11100
11111
33 13 ▶ ($handler = $cb) and last CHECK if $is_re && $str =~ $c;
Branch: 1 branch
BranchTrueFalseTotal
if $is_re and $str =~ /$c/u 3 10 13
Condition75%6/8
$is_re && $str =~ /$c/u && (($handler = $cb) && (last CHECK))
!ll&&!rl&&r
1030
$is_re and $str =~ /$c/u
!ll&&!rl&&r
643
$handler = $cb and last CHECK
!ll
03
MC/DC0%0/3
$is_re && $str =~ /$c/u && (($handler = $cb) && (last CHECK))
$is_re $str =~ /$c/u $handler = $cb
Truth table50%2/4
A and B && C
A= $is_reB= $str =~ /$c/uC= $handler = $cb
ABCresult
0XX0
10X0
1100
1111
34 }
35 }
36  
37 # Rethrow if no handler could be found
38 11 ▶ die $err unless $handler ||= $default;
Branch: 1 branch
BranchTrueFalseTotal
unless $handler ||= $default 1 10 11
Condition100%3/3
$handler ||= $default
l!l&&r!l&&!r
821
MC/DC100%2/2
$handler ||= $default
$handler $default
Truth table100%3/3
A ||= B
A= $handlerB= $default
ABresult
1X1
011
000
39 10 $handler->($_) for $err;
40  
41 10 return 1;
42 }
43  
44 65 ▶sub inspect {
Subroutine inspect: called CC=8 SCAR=20.8
Pod documented
45 65 my ($self, @sources) = @_;
46  
47 65 ▶ return $self if @{$self->line};
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->line;} 7 58 65
48  
49 # Extract file and line from message
50 58 my @files;
51 58 my $msg = $self->message;
52 58 ▶ unshift @files, [$1, $2] while $msg =~ /at\s+(.+?)\s+line\s+(\d+)/g;
Branch: 1 branch
BranchTrueFalseTotal
$msg =~ /at\s+(.+?)\s+line\s+(\d+)/gu and do { unshift @files, [$1, $2] } 71 58 129
53  
54 # Extract file and line from stack trace
55 58 ▶ if (my $zero = $self->frames->[0]) { push @files, [$zero->[1], $zero->[2]] }
Branch: 1 branch
BranchTrueFalseTotal
if (my $zero = $self->frames->[0]) 31 27 58
56  
57 # Search for context in files
58 58 for my $file (@files) {
59 74 ▶ next unless -r $file->[0] && open my $handle, '<', $file->[0];
Branch: 1 branch
BranchTrueFalseTotal
unless -r $file->[0] and open my $handle, "<", $file->[0] 34 40 74
Condition66%2/3
-r $file->[0] and open my $handle, "<", $file->[0]
!ll&&!rl&&r
34040
MC/DC50%1/2
-r $file->[0] and open my $handle, "<", $file->[0]
-r $file->[0] open my $handle, "<", $file->[0]
Truth table66%2/3
A and B
A= -r $file->[0]B= open my $handle, "<", $file->[0]
ABresult
0X0
100
111
60 40 $self->_context($file->[1], [[<$handle>]]);
61 40 return $self;
62 }
63  
64 # Search for context in sources
65 18 ▶ $self->_context($files[-1][1], [map { [split /\n/] } @sources]) if @sources;
Branch: 1 branch
BranchTrueFalseTotal
if @sources 13 5 18
66  
67 18 return $self;
68 }
69  
70 206 ▶sub new { defined $_[1] ? shift->SUPER::new(message => shift) : shift->SUPER::new }
Subroutine new: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
defined $_[1] ? : 194 12 206
71  
72 5 ▶sub raise {
Subroutine raise: called CC=5 SCAR=16.1
Pod documented
73 5 ▶ my ($class, $err) = @_ > 1 ? (@_) : (__PACKAGE__, shift);
Branch: 1 branch
BranchTrueFalseTotal
@_ > 1 ? : 4 1 5
74  
75 5 ▶ if (!$class->can('new')) { die $@ unless eval "package $class; use Mojo::Base 'Mojo::Exception'; 1" }
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 3 branches
BranchTrueFalseTotal
if (not $class->can('new')) { } 1 4 5
elsif (not $class->isa(__PACKAGE__)) { } 1 3 4
unless eval "package $class; use Mojo::Base 'Mojo::Exception'; 1" 0 1 1
76 1 elsif (!$class->isa(__PACKAGE__)) { die "$class is not a Mojo::Exception subclass" }
77  
78 4 CORE::die $class->new($err)->trace;
79 }
80  
81 194 ▶sub to_string {
Subroutine to_string: called CC=9 SCAR=22.0
Pod documented
82 194 my $self = shift;
83  
84 194 my $str = $self->message;
85  
86 194 my $frames = $self->frames;
87 194 ▶ if ($str !~ /\n$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($str =~ /\n$/u) 18 176 194
88 18 ▶ $str .= @$frames ? " at $frames->[0][1] line $frames->[0][2].\n" : "\n";
Branch: 1 branch
BranchTrueFalseTotal
@$frames ? : 10 8 18
89 }
90 194 ▶ return $str unless $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->verbose 177 17 194
91  
92 17 my $line = $self->line;
93 17 ▶ if (@$line) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$line) 16 1 17
94 16 $str .= "Context:\n";
95 16 $str .= " $_->[0]: $_->[1]\n" for @{$self->lines_before};
96 16 $str .= " $line->[0]: $line->[1]\n";
97 16 $str .= " $_->[0]: $_->[1]\n" for @{$self->lines_after};
98 }
99  
100 17 ▶ if (my $max = @$frames) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $max = @$frames) 17 0 17
101 17 $str .= "Traceback (most recent call first):\n";
102 17 $str .= qq{ File "$_->[1]", line $_->[2], in "$_->[3]"\n} for @$frames;
103 }
104  
105 17 return $str;
106 }
107  
108 3 ▶sub throw { CORE::die shift->new(shift)->trace }
Subroutine throw: called CC=1 SCAR=0.0
Pod documented
109  
110 177 ▶sub trace {
Subroutine trace: called CC=3 SCAR=11.0
Pod documented
111 177 ▶ my ($self, $start) = (shift, shift // 1);
Condition100%2/2
shift() // 1
l!l
3174
MC/DC100%1/1
shift() // 1
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
112 177 my @frames;
113 177 ▶ while (my @trace = caller($start++)) { push @frames, \@trace }
Branch: 1 branch
BranchTrueFalseTotal
if (my(@trace) = caller $start++) 5584 177 5761
114 177 return $self->frames(\@frames);
115 }
116  
117 440 ▶sub _append {
Subroutine _append: called CC=2 SCAR=7.0
118 440 my ($stack, $line) = @_;
119 440 ▶ $line = decode('UTF-8', $line) // $line;
Condition66%2/3
decode("UTF-8", $line) // $line
l!l&&r!l&&!r
43820
MC/DC0%0/2
decode("UTF-8", $line) // $line
decode("UTF-8", $line) $line
Truth table66%2/3
A // B
A= decode("UTF-8", $line)B= $line
ABresult
1X1
011
000
120 440 chomp $line;
121 440 push @$stack, $line;
122 }
123  
124 53 ▶sub _context {
Subroutine _context: called CC=10 SCAR=23.1
125 53 my ($self, $num, $sources) = @_;
126  
127 # Line
128 53 ▶ return unless defined $sources->[0][$num - 1];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sources->[0][$num - 1] 0 53 53
129 53 $self->line([$num]);
130 53 _append($self->line, $_->[$num - 1]) for @$sources;
131  
132 # Before
133 53 for my $i (2 .. 6) {
134 210 ▶ last if ((my $previous = $num - $i) < 0);
Branch: 1 branch
BranchTrueFalseTotal
if (my $previous = $num - $i) < 0 29 181 210
135 181 unshift @{$self->lines_before}, [$previous + 1];
136 181 _append($self->lines_before->[0], $_->[$previous]) for @$sources;
137 }
138  
139 # After
140 53 for my $i (0 .. 4) {
141 265 ▶ next if ((my $next = $num + $i) < 0);
Branch: 1 branch
BranchTrueFalseTotal
if (my $next = $num + $i) < 0 0 265 265
142 265 ▶ next unless defined $sources->[0][$next];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sources->[0][$next] 100 165 265
143 165 push @{$self->lines_after}, [$next + 1];
144 165 _append($self->lines_after->[-1], $_->[$next]) for @$sources;
145 }
146 }
147  
148 36 1;
149  
150 =encoding utf8
151  
152 =head1 NAME
153  
154 Mojo::Exception - Exception base class
155  
156 =head1 SYNOPSIS
157  
158 # Create exception classes
159 package MyApp::X::Foo {
160 use Mojo::Base 'Mojo::Exception';
161 }
162 package MyApp::X::Bar {
163 use Mojo::Base 'Mojo::Exception';
164 }
165  
166 # Throw exceptions and handle them gracefully
167 use Mojo::Exception qw(check);
168 eval {
169 MyApp::X::Foo->throw('Something went wrong!');
170 };
171 check $@ => [
172 'MyApp::X::Foo' => sub { say "Foo: $_" },
173 'MyApp::X::Bar' => sub { say "Bar: $_" }
174 ];
175  
176 # Generate exception classes on demand
177 use Mojo::Exception qw(check raise);
178 eval {
179 raise 'MyApp::X::Name', 'The name Minion is already taken';
180 };
181 check $@ => [
182 'MyApp::X::Name' => sub { say "Name error: $_" },
183 default => sub { say "Error: $_" }
184 ];
185  
186 =head1 DESCRIPTION
187  
188 L<Mojo::Exception> is a container for exceptions with context information.
189  
190 =head1 FUNCTIONS
191  
192 L<Mojo::Exception> implements the following functions, which can be imported individually.
193  
194 =head2 check
195  
196 my $bool = check $err => ['MyApp::X::Foo' => sub {...}];
197  
198 Process exceptions by dispatching them to handlers with one or more matching conditions. Exceptions that could not be
199 handled will be rethrown automatically.
200  
201 # Handle various types of exceptions
202 eval {
203 dangerous_code();
204 };
205 check $@ => [
206 'MyApp::X::Foo' => sub { say "Foo: $_" },
207 qr/^Could not open/ => sub { say "Open error: $_" },
208 default => sub { say "Something went wrong: $_" }
209 ];
210  
211 Matching conditions can be class names for ISA checks on exception objects, or regular expressions to match string
212 exceptions and stringified exception objects. The matching exception will be the first argument passed to the callback,
213 and is also available as C<$_>.
214  
215 # Catch MyApp::X::Foo object or a specific string exception
216 eval {
217 dangerous_code();
218 };
219 check $@ => [
220 'MyApp::X::Foo' => sub { say "Foo: $_" },
221 qr/^Could not open/ => sub { say "Open error: $_" }
222 ];
223  
224 An array reference can be used to share the same handler with multiple conditions, of which only one needs to match.
225 And since exception handlers are just callbacks, they can also throw their own exceptions.
226  
227 # Handle MyApp::X::Foo and MyApp::X::Bar the same
228 eval {
229 dangerous_code();
230 };
231 check $@ => [
232 ['MyApp::X::Foo', 'MyApp::X::Bar'] => sub { die "Foo/Bar: $_" }
233 ];
234  
235 There is currently only one keywords you can use to set special handlers. The C<default> handler is used when no other
236 handler matched.
237  
238 # Use "default" to catch everything
239 eval {
240 dangerous_code();
241 };
242 check $@ => [
243 default => sub { say "Error: $_" }
244 ];
245  
246 =head2 raise
247  
248 raise 'Something went wrong!';
249 raise 'MyApp::X::Foo', 'Something went wrong!';
250  
251 Raise a L<Mojo::Exception>, if the class does not exist yet (classes are checked for a C<new> method), one is created
252 as a L<Mojo::Exception> subclass on demand.
253  
254 =head1 ATTRIBUTES
255  
256 L<Mojo::Exception> implements the following attributes.
257  
258 =head2 frames
259  
260 my $frames = $e->frames;
261 $e = $e->frames([$frame1, $frame2]);
262  
263 Stack trace if available.
264  
265 # Extract information from the last frame
266 my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext,
267 $is_require, $hints, $bitmask, $hinthash) = @{$e->frames->[-1]};
268  
269 =head2 line
270  
271 my $line = $e->line;
272 $e = $e->line([3, 'die;']);
273  
274 The line where the exception occurred if available.
275  
276 =head2 lines_after
277  
278 my $lines = $e->lines_after;
279 $e = $e->lines_after([[4, 'say $foo;'], [5, 'say $bar;']]);
280  
281 Lines after the line where the exception occurred if available.
282  
283 =head2 lines_before
284  
285 my $lines = $e->lines_before;
286 $e = $e->lines_before([[1, 'my $foo = 23;'], [2, 'my $bar = 24;']]);
287  
288 Lines before the line where the exception occurred if available.
289  
290 =head2 message
291  
292 my $msg = $e->message;
293 $e = $e->message('Died at test.pl line 3.');
294  
295 Exception message, defaults to C<Exception!>.
296  
297 =head2 verbose
298  
299 my $bool = $e->verbose;
300 $e = $e->verbose($bool);
301  
302 Show more information with L</"to_string">, such as L</"frames">, defaults to the value of the
303 C<MOJO_EXCEPTION_VERBOSE> environment variable.
304  
305 =head1 METHODS
306  
307 L<Mojo::Exception> inherits all methods from L<Mojo::Base> and implements the following new ones.
308  
309 =head2 inspect
310  
311 $e = $e->inspect;
312 $e = $e->inspect($source1, $source2);
313  
314 Inspect L</"message">, L</"frames"> and optional additional sources to fill L</"lines_before">, L</"line"> and
315 L</"lines_after"> with context information.
316  
317 =head2 new
318  
319 my $e = Mojo::Exception->new;
320 my $e = Mojo::Exception->new('Died at test.pl line 3.');
321  
322 Construct a new L<Mojo::Exception> object and assign L</"message"> if necessary.
323  
324 =head2 to_string
325  
326 my $str = $e->to_string;
327  
328 Render exception. Note that the output format may change as more features are added, only the error message at the
329 beginning is guaranteed not to be modified to allow regex matching.
330  
331 =head2 throw
332  
333 Mojo::Exception->throw('Something went wrong!');
334  
335 Throw exception from the current execution context.
336  
337 # Longer version
338 die Mojo::Exception->new('Something went wrong!')->trace;
339  
340 =head2 trace
341  
342 $e = $e->trace;
343 $e = $e->trace($skip);
344  
345 Generate stack trace and store all L</"frames">, defaults to skipping C<1> call frame.
346  
347 # Skip 3 call frames
348 $e->trace(3);
349  
350 # Skip no call frames
351 $e->trace(0);
352  
353 =head1 OPERATORS
354  
355 L<Mojo::Exception> overloads the following operators.
356  
357 =head2 bool
358  
359 my $bool = !!$e;
360  
361 Always true.
362  
363 =head2 stringify
364  
365 my $str = "$e";
366  
367 Alias for L</"to_string">.
368  
369 =head1 SEE ALSO
370  
371 L<Mojolicious>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
372  
373 =cut
« Mojo/Content.pm ↑ Summary Mojo/Transaction.pm »