in reply to Best practices for handling errors

In fact, after reading eyepopslikeamosquito’s response I'm reminded of this kind of approach. It’s not very hard, it can DWIW a little with overload, and it can be very useful/robust compared to matching for content against error strings–

use 5.014; # Safer eval+$@ handling. use strictures; package HURR_DERR_ERR { use Moo; use Devel::StackTrace; use overload '""' => sub { +shift->as_string }; has code => is => "ro", default => sub { "[uncoded]" }; has message => is => "ro", required => 1; has stacktrace => is => "ro", default => sub { Devel::StackTrace->new->as_string }; sub as_string { my $self = shift; join ": ", $self->code, $self->message; } }; for ( 1 .. 100 ) { eval { die HURR_DERR_ERR->new( message => "Unlucky number encountered +: $_" ) if /\b4\b/; # You'll have to localize if you don't want Ch +inese values. }; if ( $@ ) { # If you want it -> say $@->stacktrace; die "Got an error -> $@"; } else { say; } }
1 2 3 Got an error -> [uncoded]: Unlucky number encountered: 4 at example.pl + line 33.

Update: changed “script name” in error output. Update #2: changed version per suggestion.

Replies are listed 'Best First'.
Re^2: Best practices for handling errors
by Anonymous Monk on Sep 27, 2014 at 23:34 UTC

    You might want to make that use 5.014;, since that's when eval {...}; if ($@) {...} became safe(r) (see Exception Handling).

      Good note. I use 5.16 and 5.20 normally. The 5.12 was boilerplate and I considered using Try/Try::Tiny in it but the example was long enough already.