in reply to Re: How to print the backtrace in a "catch" block?
in thread How to print the backtrace in a "catch" block?

Well, this is what I'm getting:
runtime error at - line 6. the transaction failed at - line 23 main::main_sub() called at - line 27
What I'm hoping for:
runtime error at - line 6. the transaction failed at - line 23 main::sub3() called at - line 3 main::sub1() called at - line 13 main::main_sub() called at - line 27
Or perhaps in Ruby code:
def dying_sub raise RuntimeError, "reason here" end def main begin dying_sub() rescue RuntimeError => e STDERR.puts e.backtrace end end main() # Output: # test.rb:2:in `dying_sub' # test.rb:7:in `main' # test.rb:13

Replies are listed 'Best First'.
Re^3: How to print the backtrace in a "catch" block?
by Corion (Patriarch) on Jan 16, 2012 at 16:18 UTC

    You will need to replace the die in sub2 and/or sub3 with a call to confess to get at the stack trace. Maybe you can install a $SIG{__DIE__} handler that stashes away the stack trace for later retrieval. I think that Carp::Always does this, but I've never used it.

      $SIG{__DIE__} = sub { cluck shift; }
      did in fact do what I want (just need to make it look nicer). Thanks

        This looks nicer. It's got a winking open-mouthed smiley and a bug-eyed tongue-sticking-out smiley.

        $SIG{__DIE__} = sub { cluck shift ;-0 } or 8-P ;
      I looked at some of my code...
      It is possible to install a localized $SIG handler.
      In my case a stack trace means next to nothing..I want to know the exact DB record the failure happened on..that means something!

      In this code, I just have a __WARN__ handler, but I would presume that __DIE__ would be possible also. Of course $x has to be in scope for the $SIG handler!

      Anyway, installing a __DIE__ handler in the sub() might be easier and even better than a stack trace - although that could be done in the handler also. In this code, I just want to know which of 1M DB records caused the Warning - its not fatal for this code, but it is something I have to find and fix later. Just an idea....

      sub x { my ($x) = @_; # $x is an array ref to a DB record local $SIG{__WARN__} = sub { my $msg = shift; print STDERR "*******\n"; print STDERR $msg; print STDERR "current DB record: id=", $x->[ID]; }; # some stuff that might cause a Warning.... # some operations on the record pointed to by $x # maybe "abc123" is not numeric, etc. return $result; }

      Thanks, I suppose I'll try the signal approach. (I'm obviously not dying on purpose, but Perl is dying for me.) Was looking at Carp::Always's source code earlier, and that's what it uses.