Perl: Best practice for handling eval errors in a package

When working with the Perl module (CPAN), I often find that I want to implement error handling the same way for all method calls (for example, auto-retry for certain error codes, writing some of them, death to others)). The code looks very repeating:

my $result1 = eval{ $obj->method1 ( @arg ); }; if ( $@ ) { # error handling code } my $result2 = eval{ $obj->method2 ( @arg ); }; if ( $@ ) { # error handling code } 

Is there a way to automate this? One way that seems to work is to use sub {}:

 sub error_handler { my $method = shift; my $result = eval{ shift()->$method ( @_ ); }; if ( $@ ) { # error handling code } else { return ( $result ); } } my $result1 = error_handler ( 'method1', $obj, @arg ); my $result2 = error_handler ( 'method2', $obj, @arg ); 

But I still find this code tedious. Another idea I had was to try expanding the package:

 package My::Package; use Moo; extends 'Package'; our $AUTOLOAD; sub AUTOLOAD { $AUTOLOAD =~ s/^My::Package:://; my $result = eval{ no strict 'refs'; shift()->$AUTOLOAD ( @_ ); }; if ( $@ ) { # error handling code } else { return ( $result ); } } 

But this code does not work - I need a way only for public AUTOLOAD methods. Anyone have a solution?

+4
source share
1 answer

Your first method is the best. Or you can make a slightly more beautiful change with Try or Try :: Tiny , which both work to reduce the verbosity of your second method.

The main reason to avoid your second and third methods has less to do with the verbosity of your code (which, I admit, is annoying in the first method), and is more dependent on the readability of your code.

If you end up expanding every class that you import, your code will be almost completely unreadable to someone else or worse: it will seem readable ("Oh, I know how MIME :: Parse!" Works), but not will do what was expected ("Hmm, why doesn't MIME :: Parse fail with this bad input?")

The second method has essentially the same problem, but at least it does not claim to not handle errors. But it still makes debugging a lot harder.

I know that re-entering the same error handling code is often annoying (I do this all the time!), But this is best practice.

+2
source

All Articles