Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Best practices for handling errors

by Your Mother (Archbishop)
on Sep 27, 2014 at 23:03 UTC ( [id://1102247]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1102247]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (7)
As of 2024-03-28 18:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found