How to catch and reinstall error in Perl?

Say I have a module pane, which is a subclass wrapper for a Foo module. I want calls to Bar methods to accurately mimic Foo - right down to fatal errors. Still easy enough; I just call the SUPER method.


sub stuff {
    # Do stuff here

    SUPER::stuff(@_);

    # Do more stuff here
}

But let's say that I want to catch, register and reconstruct any fatal errors SUPER::stuff(). The first two steps are simple:


sub stuff {
    # Do stuff here

    eval {
        SUPER::stuff(@_);
    };
    $@ and log("Naughty, naughty: $@");

    # Do more stuff here
}

... but I don’t know how to do the last part. How to throw an error so that the caller cannot distinguish between the call Foo->stuff()and the call Bar->stuff()? Can I just paste die $@after the log statement and expect it to do what I want, or are there any nuances here that are likely to put me in trouble?

+3
source share
3

eval/catch/log/rethrow Perl .

sub stuff {
    # Do stuff here

    local $@; # don't reset $@ for our caller.
    my $eval_ok = eval { # get the return from eval, it will be undef if the eval catches an error.
        SUPER::stuff(@_);
        1; # return 1 (true) if there are no errors caught.
    };
    if (!$eval_ok) { # don't trust $@ it might have been reset as the eval unrolled.
        my $error = $@ || 'unknown error'; # copy $@ incase write_log resets $@, or is later changed to cause it to reset $@.
        write_log("Naughty, naughty: $error");
        die $error; # after all that we can rethrow our error.
    }

    # Do more stuff here
}

Try:: Tiny, mob :

sub stuff {
    # Do stuff here

    try {
        SUPER::stuff(@_);
    } catch {
        my $error = $_;
        write_log("Naughty, naughty: $error");
        die $error;
    }

    # Do more stuff here
}
+4

, , . Perl , $@ - , .

+1
 eval {
        SUPER::stuff(@_);
    };
    $@ and ( log("Naughty, naughty: $@"), die $@ );
+1
source

All Articles