Use Carp's croak and carp instead of die and warn, and then you can optionally turn on the stack traces as documented in Forcing a Stack Trace. Don't build your own stack traces.

As always TIMTOWTDI, but here's how I might do what you asked:

This last point is something I've learned from my experience with exceptions: If the exceptions are designed properly, meaning they are true errors and not a normal mechanism to return values, then very rarely should any layer of my program be catching exceptions without re-throwing them except the very outermost layer. In a GUI, I'd like errors to be displayed to a user, in a daemon, they need to go into a log or email, and in command-line programs, they need to be displayed on the console. If a program has both (a) "exceptions" that mean something went very wrong and the program needs to terminate and (b) "exceptions" that mean a particular operation failed and the program may continue running, there needs to be a clear way for the program to distinguish these two types of exceptions. One way to do that is have (a) be fatal errors (e.g. die and friends) and (b) be special return values (e.g. undef). Sometimes you might be working with external libraries that take a different approach than yours, meaning they die more often, or they never die and return undef instead, that's one case where I might "transform" these exceptions using eval { ... ; 1} or return undef or defined(my $x = foo()) or die "foo() failed".


In reply to Re^3: Best practices for handling errors by Anonymous Monk
in thread Best practices for handling errors by v_melnik

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.