in reply to style for returning errors from subroutines

I guess I like the minimalist approach, by making the subroutine code as uncoupled as possible from the error handling code. This isn't always easy or possible though, so YMMV.

For example, if an error is fatal, I like to have the sub that generated it 'die' (or croak) right away. If the code is used in a short lived script that's good enough. If it is is something that needs to be more "macho", I'll try to get away with logging, generating caller info, etc by defining my own $SIG{__DIE__} proc in the caller -- that way the sub code stays simple. If I end up calling someone else's package that happens to die, I don't have to wrap it in an eval block just to log the message (i.e. timelocal). (Of course I'll need to use eval if I don't really want it to die.)

Handling non-fatal errors is harder. You could use $SIG{__WARN__} to handle logging them, but you'll still need to do something like your method above of storing off the message somewhere until you finally report it. One way to do this might be to have the $SIG{__WARN__} proc save off the message, without displaying it and then have the caller decide whether or not it's worth reporting.

FWIW, you may want to use "or" instead of "||" in your cases above. It turns code that looks like this...

($a = foo()) || bar();
... to ...
$a = foo() or bar();
Which may (or may not) be easier to read.

Replies are listed 'Best First'.
Re: Re: style for returning errors from subroutines
by Boldra (Curate) on Jun 14, 2001 at 20:23 UTC
    So far this looks like the most attractive idea to me.

    The code stays very clean, with all the error-handling kept out of the main routine and the loose coupling is certainly a bonus. It also looks like it would work beautifully with Carp for extra verbosity in the errors.

    My || usage is just a habit now; I might think about changing it. I do prefer to use the extra brackets though, even if they aren't always needed.

    Thanks for the suggestion. If that Serbian contractor hadn't pinched my camel book, I might have figured it out myself :)