9a40de95545d2b8fbc5523c37641e3dd8a03ce6a
[p5sagit/Try-Tiny.git] / lib / Try / Tiny.pm
1 package Try::Tiny;
2 use 5.006;
3 # ABSTRACT: Minimal try/catch with proper preservation of $@
4
5 our $VERSION = '0.29';
6
7 use strict;
8 use warnings;
9
10 use Exporter 5.57 'import';
11 our @EXPORT = our @EXPORT_OK = qw(try catch finally);
12
13 use Carp;
14 $Carp::Internal{+__PACKAGE__}++;
15
16 BEGIN {
17   my $su = $INC{'Sub/Util.pm'} && defined &Sub::Util::set_subname;
18   my $sn = $INC{'Sub/Name.pm'} && eval { Sub::Name->VERSION(0.08) };
19   unless ($su || $sn) {
20     $su = eval { require Sub::Util; } && defined &Sub::Util::set_subname;
21     unless ($su) {
22       $sn = eval { require Sub::Name; Sub::Name->VERSION(0.08) };
23     }
24   }
25
26   *_subname = $su ? \&Sub::Util::set_subname
27             : $sn ? \&Sub::Name::subname
28             : sub { $_[1] };
29   *_HAS_SUBNAME = ($su || $sn) ? sub(){1} : sub(){0};
30 }
31
32 my %_finally_guards;
33
34 # Need to prototype as @ not $$ because of the way Perl evaluates the prototype.
35 # Keeping it at $$ means you only ever get 1 sub because we need to eval in a list
36 # context & not a scalar one
37
38 sub try (&;@) {
39   my ( $try, @code_refs ) = @_;
40
41   # we need to save this here, the eval block will be in scalar context due
42   # to $failed
43   my $wantarray = wantarray;
44
45   # work around perl bug by explicitly initializing these, due to the likelyhood
46   # this will be used in global destruction (perl rt#119311)
47   my ( $catch, @finally ) = ();
48
49   # find labeled blocks in the argument list.
50   # catch and finally tag the blocks by blessing a scalar reference to them.
51   foreach my $code_ref (@code_refs) {
52
53     if ( ref($code_ref) eq 'Try::Tiny::Catch' ) {
54       croak 'A try() may not be followed by multiple catch() blocks'
55         if $catch;
56       $catch = ${$code_ref};
57     } elsif ( ref($code_ref) eq 'Try::Tiny::Finally' ) {
58       push @finally, ${$code_ref};
59     } else {
60       croak(
61         'try() encountered an unexpected argument ('
62       . ( defined $code_ref ? $code_ref : 'undef' )
63       . ') - perhaps a missing semi-colon before or'
64       );
65     }
66   }
67
68   # FIXME consider using local $SIG{__DIE__} to accumulate all errors. It's
69   # not perfect, but we could provide a list of additional errors for
70   # $catch->();
71
72   # name the blocks if we have Sub::Name installed
73   _subname(caller.'::try {...} ' => $try)
74     if _HAS_SUBNAME;
75
76   # set up scope guards to invoke the finally blocks at the end.
77   # this should really be a function scope lexical variable instead of
78   # file scope + local but that causes issues with perls < 5.20 due to
79   # perl rt#119311
80   local $_finally_guards{guards} = [
81     map { Try::Tiny::ScopeGuard->_new($_) }
82     @finally
83   ];
84
85   # save the value of $@ so we can set $@ back to it in the beginning of the eval
86   # and restore $@ after the eval finishes
87   my $prev_error = $@;
88
89   my ( @ret, $error );
90
91   # failed will be true if the eval dies, because 1 will not be returned
92   # from the eval body
93   my $failed = not eval {
94     $@ = $prev_error;
95
96     # evaluate the try block in the correct context
97     if ( $wantarray ) {
98       @ret = $try->();
99     } elsif ( defined $wantarray ) {
100       $ret[0] = $try->();
101     } else {
102       $try->();
103     };
104
105     return 1; # properly set $failed to false
106   };
107
108   # preserve the current error and reset the original value of $@
109   $error = $@;
110   $@ = $prev_error;
111
112   # at this point $failed contains a true value if the eval died, even if some
113   # destructor overwrote $@ as the eval was unwinding.
114   if ( $failed ) {
115     # pass $error to the finally blocks
116     push @$_, $error for @{$_finally_guards{guards}};
117
118     # if we got an error, invoke the catch block.
119     if ( $catch ) {
120       # This works like given($error), but is backwards compatible and
121       # sets $_ in the dynamic scope for the body of C<$catch>
122       for ($error) {
123         return $catch->($error);
124       }
125
126       # in case when() was used without an explicit return, the C<for>
127       # loop will be aborted and there's no useful return value
128     }
129
130     return;
131   } else {
132     # no failure, $@ is back to what it was, everything is fine
133     return $wantarray ? @ret : $ret[0];
134   }
135 }
136
137 sub catch (&;@) {
138   my ( $block, @rest ) = @_;
139
140   croak 'Useless bare catch()' unless wantarray;
141
142   _subname(caller.'::catch {...} ' => $block)
143     if _HAS_SUBNAME;
144   return (
145     bless(\$block, 'Try::Tiny::Catch'),
146     @rest,
147   );
148 }
149
150 sub finally (&;@) {
151   my ( $block, @rest ) = @_;
152
153   croak 'Useless bare finally()' unless wantarray;
154
155   _subname(caller.'::finally {...} ' => $block)
156     if _HAS_SUBNAME;
157   return (
158     bless(\$block, 'Try::Tiny::Finally'),
159     @rest,
160   );
161 }
162
163 {
164   package # hide from PAUSE
165     Try::Tiny::ScopeGuard;
166
167   use constant UNSTABLE_DOLLARAT => ("$]" < '5.013002') ? 1 : 0;
168
169   sub _new {
170     shift;
171     bless [ @_ ];
172   }
173
174   sub DESTROY {
175     my ($code, @args) = @{ $_[0] };
176
177     local $@ if UNSTABLE_DOLLARAT;
178     eval {
179       $code->(@args);
180       1;
181     } or do {
182       warn
183         "Execution of finally() block $code resulted in an exception, which "
184       . '*CAN NOT BE PROPAGATED* due to fundamental limitations of Perl. '
185       . 'Your program will continue as if this event never took place. '
186       . "Original exception text follows:\n\n"
187       . (defined $@ ? $@ : '$@ left undefined...')
188       . "\n"
189       ;
190     }
191   }
192 }
193
194 __PACKAGE__
195
196 __END__
197
198 =pod
199
200 =head1 SYNOPSIS
201
202 You can use Try::Tiny's C<try> and C<catch> to expect and handle exceptional
203 conditions, avoiding quirks in Perl and common mistakes:
204
205   # handle errors with a catch handler
206   try {
207     die "foo";
208   } catch {
209     warn "caught error: $_"; # not $@
210   };
211
212 You can also use it like a standalone C<eval> to catch and ignore any error
213 conditions.  Obviously, this is an extreme measure not to be undertaken
214 lightly:
215
216   # just silence errors
217   try {
218     die "foo";
219   };
220
221 =head1 DESCRIPTION
222
223 This module provides bare bones C<try>/C<catch>/C<finally> statements that are designed to
224 minimize common mistakes with eval blocks, and NOTHING else.
225
226 This is unlike L<TryCatch> which provides a nice syntax and avoids adding
227 another call stack layer, and supports calling C<return> from the C<try> block to
228 return from the parent subroutine. These extra features come at a cost of a few
229 dependencies, namely L<Devel::Declare> and L<Scope::Upper> which are
230 occasionally problematic, and the additional catch filtering uses L<Moose>
231 type constraints which may not be desirable either.
232
233 The main focus of this module is to provide simple and reliable error handling
234 for those having a hard time installing L<TryCatch>, but who still want to
235 write correct C<eval> blocks without 5 lines of boilerplate each time.
236
237 It's designed to work as correctly as possible in light of the various
238 pathological edge cases (see L</BACKGROUND>) and to be compatible with any style
239 of error values (simple strings, references, objects, overloaded objects, etc).
240
241 If the C<try> block dies, it returns the value of the last statement executed in
242 the C<catch> block, if there is one. Otherwise, it returns C<undef> in scalar
243 context or the empty list in list context. The following examples all
244 assign C<"bar"> to C<$x>:
245
246   my $x = try { die "foo" } catch { "bar" };
247   my $x = try { die "foo" } || "bar";
248   my $x = (try { die "foo" }) // "bar";
249
250   my $x = eval { die "foo" } || "bar";
251
252 You can add C<finally> blocks, yielding the following:
253
254   my $x;
255   try { die 'foo' } finally { $x = 'bar' };
256   try { die 'foo' } catch { warn "Got a die: $_" } finally { $x = 'bar' };
257
258 C<finally> blocks are always executed making them suitable for cleanup code
259 which cannot be handled using local.  You can add as many C<finally> blocks to a
260 given C<try> block as you like.
261
262 Note that adding a C<finally> block without a preceding C<catch> block
263 suppresses any errors. This behaviour is consistent with using a standalone
264 C<eval>, but it is not consistent with C<try>/C<finally> patterns found in
265 other programming languages, such as Java, Python, Javascript or C#. If you
266 learnt the C<try>/C<finally> pattern from one of these languages, watch out for
267 this.
268
269 =head1 EXPORTS
270
271 All functions are exported by default using L<Exporter>.
272
273 If you need to rename the C<try>, C<catch> or C<finally> keyword consider using
274 L<Sub::Import> to get L<Sub::Exporter>'s flexibility.
275
276 =over 4
277
278 =item try (&;@)
279
280 Takes one mandatory C<try> subroutine, an optional C<catch> subroutine and C<finally>
281 subroutine.
282
283 The mandatory subroutine is evaluated in the context of an C<eval> block.
284
285 If no error occurred the value from the first block is returned, preserving
286 list/scalar context.
287
288 If there was an error and the second subroutine was given it will be invoked
289 with the error in C<$_> (localized) and as that block's first and only
290 argument.
291
292 C<$@> does B<not> contain the error. Inside the C<catch> block it has the same
293 value it had before the C<try> block was executed.
294
295 Note that the error may be false, but if that happens the C<catch> block will
296 still be invoked.
297
298 Once all execution is finished then the C<finally> block, if given, will execute.
299
300 =item catch (&;@)
301
302 Intended to be used in the second argument position of C<try>.
303
304 Returns a reference to the subroutine it was given but blessed as
305 C<Try::Tiny::Catch> which allows try to decode correctly what to do
306 with this code reference.
307
308   catch { ... }
309
310 Inside the C<catch> block the caught error is stored in C<$_>, while previous
311 value of C<$@> is still available for use.  This value may or may not be
312 meaningful depending on what happened before the C<try>, but it might be a good
313 idea to preserve it in an error stack.
314
315 For code that captures C<$@> when throwing new errors (i.e.
316 L<Class::Throwable>), you'll need to do:
317
318   local $@ = $_;
319
320 =item finally (&;@)
321
322   try     { ... }
323   catch   { ... }
324   finally { ... };
325
326 Or
327
328   try     { ... }
329   finally { ... };
330
331 Or even
332
333   try     { ... }
334   finally { ... }
335   catch   { ... };
336
337 Intended to be the second or third element of C<try>. C<finally> blocks are always
338 executed in the event of a successful C<try> or if C<catch> is run. This allows
339 you to locate cleanup code which cannot be done via C<local()> e.g. closing a file
340 handle.
341
342 When invoked, the C<finally> block is passed the error that was caught.  If no
343 error was caught, it is passed nothing.  (Note that the C<finally> block does not
344 localize C<$_> with the error, since unlike in a C<catch> block, there is no way
345 to know if C<$_ == undef> implies that there were no errors.) In other words,
346 the following code does just what you would expect:
347
348   try {
349     die_sometimes();
350   } catch {
351     # ...code run in case of error
352   } finally {
353     if (@_) {
354       print "The try block died with: @_\n";
355     } else {
356       print "The try block ran without error.\n";
357     }
358   };
359
360 B<You must always do your own error handling in the C<finally> block>. C<Try::Tiny> will
361 not do anything about handling possible errors coming from code located in these
362 blocks.
363
364 Furthermore B<exceptions in C<finally> blocks are not trappable and are unable
365 to influence the execution of your program>. This is due to limitation of
366 C<DESTROY>-based scope guards, which C<finally> is implemented on top of. This
367 may change in a future version of Try::Tiny.
368
369 In the same way C<catch()> blesses the code reference this subroutine does the same
370 except it bless them as C<Try::Tiny::Finally>.
371
372 =back
373
374 =head1 BACKGROUND
375
376 There are a number of issues with C<eval>.
377
378 =head2 Clobbering $@
379
380 When you run an C<eval> block and it succeeds, C<$@> will be cleared, potentially
381 clobbering an error that is currently being caught.
382
383 This causes action at a distance, clearing previous errors your caller may have
384 not yet handled.
385
386 C<$@> must be properly localized before invoking C<eval> in order to avoid this
387 issue.
388
389 More specifically, C<$@> is clobbered at the beginning of the C<eval>, which
390 also makes it impossible to capture the previous error before you die (for
391 instance when making exception objects with error stacks).
392
393 For this reason C<try> will actually set C<$@> to its previous value (the one
394 available before entering the C<try> block) in the beginning of the C<eval>
395 block.
396
397 =head2 Localizing $@ silently masks errors
398
399 Inside an C<eval> block, C<die> behaves sort of like:
400
401   sub die {
402     $@ = $_[0];
403     return_undef_from_eval();
404   }
405
406 This means that if you were polite and localized C<$@> you can't die in that
407 scope, or your error will be discarded (printing "Something's wrong" instead).
408
409 The workaround is very ugly:
410
411   my $error = do {
412     local $@;
413     eval { ... };
414     $@;
415   };
416
417   ...
418   die $error;
419
420 =head2 $@ might not be a true value
421
422 This code is wrong:
423
424   if ( $@ ) {
425     ...
426   }
427
428 because due to the previous caveats it may have been unset.
429
430 C<$@> could also be an overloaded error object that evaluates to false, but
431 that's asking for trouble anyway.
432
433 The classic failure mode is:
434
435   sub Object::DESTROY {
436     eval { ... }
437   }
438
439   eval {
440     my $obj = Object->new;
441
442     die "foo";
443   };
444
445   if ( $@ ) {
446
447   }
448
449 In this case since C<Object::DESTROY> is not localizing C<$@> but still uses
450 C<eval>, it will set C<$@> to C<"">.
451
452 The destructor is called when the stack is unwound, after C<die> sets C<$@> to
453 C<"foo at Foo.pm line 42\n">, so by the time C<if ( $@ )> is evaluated it has
454 been cleared by C<eval> in the destructor.
455
456 The workaround for this is even uglier than the previous ones. Even though we
457 can't save the value of C<$@> from code that doesn't localize, we can at least
458 be sure the C<eval> was aborted due to an error:
459
460   my $failed = not eval {
461     ...
462
463     return 1;
464   };
465
466 This is because an C<eval> that caught a C<die> will always return a false
467 value.
468
469 =head1 SHINY SYNTAX
470
471 Using Perl 5.10 you can use L<perlsyn/"Switch statements">.
472
473 =for stopwords topicalizer
474
475 The C<catch> block is invoked in a topicalizer context (like a C<given> block),
476 but note that you can't return a useful value from C<catch> using the C<when>
477 blocks without an explicit C<return>.
478
479 This is somewhat similar to Perl 6's C<CATCH> blocks. You can use it to
480 concisely match errors:
481
482   try {
483     require Foo;
484   } catch {
485     when (/^Can't locate .*?\.pm in \@INC/) { } # ignore
486     default { die $_ }
487   };
488
489 =head1 CAVEATS
490
491 =over 4
492
493 =item *
494
495 C<@_> is not available within the C<try> block, so you need to copy your
496 argument list. In case you want to work with argument values directly via C<@_>
497 aliasing (i.e. allow C<$_[1] = "foo">), you need to pass C<@_> by reference:
498
499   sub foo {
500     my ( $self, @args ) = @_;
501     try { $self->bar(@args) }
502   }
503
504 or
505
506   sub bar_in_place {
507     my $self = shift;
508     my $args = \@_;
509     try { $_ = $self->bar($_) for @$args }
510   }
511
512 =item *
513
514 C<return> returns from the C<try> block, not from the parent sub (note that
515 this is also how C<eval> works, but not how L<TryCatch> works):
516
517   sub parent_sub {
518     try {
519       die;
520     }
521     catch {
522       return;
523     };
524
525     say "this text WILL be displayed, even though an exception is thrown";
526   }
527
528 Instead, you should capture the return value:
529
530   sub parent_sub {
531     my $success = try {
532       die;
533       1;
534     };
535     return unless $success;
536
537     say "This text WILL NEVER appear!";
538   }
539   # OR
540   sub parent_sub_with_catch {
541     my $success = try {
542       die;
543       1;
544     }
545     catch {
546       # do something with $_
547       return undef; #see note
548     };
549     return unless $success;
550
551     say "This text WILL NEVER appear!";
552   }
553
554 Note that if you have a C<catch> block, it must return C<undef> for this to work,
555 since if a C<catch> block exists, its return value is returned in place of C<undef>
556 when an exception is thrown.
557
558 =item *
559
560 C<try> introduces another caller stack frame. L<Sub::Uplevel> is not used. L<Carp>
561 will not report this when using full stack traces, though, because
562 C<%Carp::Internal> is used. This lack of magic is considered a feature.
563
564 =for stopwords unhygienically
565
566 =item *
567
568 The value of C<$_> in the C<catch> block is not guaranteed to be the value of
569 the exception thrown (C<$@>) in the C<try> block.  There is no safe way to
570 ensure this, since C<eval> may be used unhygienically in destructors.  The only
571 guarantee is that the C<catch> will be called if an exception is thrown.
572
573 =item *
574
575 The return value of the C<catch> block is not ignored, so if testing the result
576 of the expression for truth on success, be sure to return a false value from
577 the C<catch> block:
578
579   my $obj = try {
580     MightFail->new;
581   } catch {
582     ...
583
584     return; # avoid returning a true value;
585   };
586
587   return unless $obj;
588
589 =item *
590
591 C<$SIG{__DIE__}> is still in effect.
592
593 Though it can be argued that C<$SIG{__DIE__}> should be disabled inside of
594 C<eval> blocks, since it isn't people have grown to rely on it. Therefore in
595 the interests of compatibility, C<try> does not disable C<$SIG{__DIE__}> for
596 the scope of the error throwing code.
597
598 =item *
599
600 Lexical C<$_> may override the one set by C<catch>.
601
602 For example Perl 5.10's C<given> form uses a lexical C<$_>, creating some
603 confusing behavior:
604
605   given ($foo) {
606     when (...) {
607       try {
608         ...
609       } catch {
610         warn $_; # will print $foo, not the error
611         warn $_[0]; # instead, get the error like this
612       }
613     }
614   }
615
616 Note that this behavior was changed once again in L<Perl5 version 18
617 |https://metacpan.org/module/perldelta#given-now-aliases-the-global-_>.
618 However, since the entirety of lexical C<$_> is now L<considered experimental
619 |https://metacpan.org/module/perldelta#Lexical-_-is-now-experimental>, it
620 is unclear whether the new version 18 behavior is final.
621
622 =back
623
624 =head1 SEE ALSO
625
626 =over 4
627
628 =item L<TryCatch>
629
630 Much more feature complete, more convenient semantics, but at the cost of
631 implementation complexity.
632
633 =item L<autodie>
634
635 Automatic error throwing for builtin functions and more. Also designed to
636 work well with C<given>/C<when>.
637
638 =item L<Throwable>
639
640 A lightweight role for rolling your own exception classes.
641
642 =item L<Error>
643
644 Exception object implementation with a C<try> statement. Does not localize
645 C<$@>.
646
647 =item L<Exception::Class::TryCatch>
648
649 Provides a C<catch> statement, but properly calling C<eval> is your
650 responsibility.
651
652 The C<try> keyword pushes C<$@> onto an error stack, avoiding some of the
653 issues with C<$@>, but you still need to localize to prevent clobbering.
654
655 =back
656
657 =head1 LIGHTNING TALK
658
659 I gave a lightning talk about this module, you can see the slides (Firefox
660 only):
661
662 L<http://web.archive.org/web/20100628040134/http://nothingmuch.woobling.org/talks/takahashi.xul>
663
664 Or read the source:
665
666 L<http://web.archive.org/web/20100305133605/http://nothingmuch.woobling.org/talks/yapc_asia_2009/try_tiny.yml>
667
668 =cut