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.

In reply to Re: style for returning errors from subroutines by bluto
in thread style for returning errors from subroutines by Boldra

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.