perlerror-handlingcatalystdbix-classtemplate-toolkit

How do I handle errors in methods chains in Perl?


What is the best way to deal with exceptions threw in a method chaining in Perl? I want to assign a value of 0 or undef if any of the methods chained throw an exception

Code sample:

my $x = $obj->get_obj->get_other_obj->get_another_obj->do_something;

What the best way to do it? Do I have to wrap in a try/catch/finally statement everytime? The context I want to apply this is: Im working in web development using Catalyst and DBIC and I do a lot of chained resultsets and if some of this resultset throw an exception I just want to assign a value of 0 or undef and then treat this error in the template (Im using Template Toolkit). If there is another way to do that without wrapping every call in try/catch, please let me know. If you know a better way to treat this type of error in the same context (Catalyst/DBIC/TT), please suggest. A practical example would be when the user search for something and this does not exists.


Solution

  • I handle this by returning a null object at the point of failure. That object responds to every method by simply returning itself, so it keeps doing that until it eats up the remaining methods. At the end, you look in $x to see if it's the result you expected or this null object.

    Here's an example of such a thing:

    use v5.12;
    
    package Null {
        my $null = bless {}, __PACKAGE__;
        sub DESTROY { 1 }
        sub AUTOLOAD { $null }
        }
    

    For every method called, the AUTOLOAD intercepts it and returns the empty object.

    When you run into an error, you return one of these Null objects. In the middle of a method chain you still get an object back so Perl doesn't blow up when you call the next method.

    sub get_other_obj {
        ...;
        return Null->new if $error;
        ...;
        }
    

    At the end of the chain, you can check what you got back to see if it's a Null object. If that's what you got, something bad happened.

    That's the basic idea. You can improve on the Null class to make it remember a message and where it was created, or add some polymorphic methods (such as sub is_success { 0 }) to make it play nicely with the interfaces of the objects you expected to get.

    I thought I had written something long about this somewhere, but now I can't find it.

    UPDATE: found some of those writings: