in reply to Getting croak to show both caller and callee?

Thanks for the replies.

And just to clarify, I *can* get what I need by correctly using croak/die/confess/warn in the appropriate places or by adding additional details to the actual exception message. This is more a question of DWIW when we mistakenly use croak() in a spot where die() would been more informative.

Here's some example code. And yes, it's completely insecure; it's just to demonstrate the issue.

#!/usr/bin/env perl { package MyModule; use strict; use warnings; use Carp; sub a { croak 'croaking' } sub b { die 'dying' } sub dispatch { my $class = shift; my $method = shift or croak 'no method name supplied'; $class->$method; } } while (<>) { chomp; next unless /\S/; eval { MyModule->dispatch($_) }; warn $@ if $@; }

If you run it and enter 'b', you'll see: "dying at ./try line 11, <> line 2." Line 11 is in fact the b() routine, so that's great.

Now enter 'a' and you get: "croaking at ./try line 25." That is not helpful, since line 25 is just the dispatch routine. We have no idea what was dispatched that raised the error.

So ideally, what I would like to see is the first two call frames of the stack, rather than only the second.

IOW, croak() would emit something like this by default:

croaking at ./try line 12, <> line 1.
	MyModule::a("MyModule") called at ./try line 19

Any thoughts on how to accomplish that?

Thanks!

Replies are listed 'Best First'.
Re^2: Getting croak to show both caller and callee?
by Athanasius (Archbishop) on Apr 26, 2015 at 07:26 UTC
    Any thoughts on how to accomplish that?

    Here’s one: Change use Carp; to use MyCarp; and put the module “MyCarp.pm” somewhere in your Perl’s path:

    #! perl package MyCarp; use strict; use warnings; use Exporter 'import'; our @EXPORT = 'croak'; sub croak { use Carp 'shortmess'; $Carp::Verbose = 1; my @lines = split /\n/, shortmess @_; s/^\s+// for @lines; die $lines[1] . "\n\t" . $lines[2] . "\n"; } 1;

    Example output:

    17:22 >perl 1229_SoPW.pl b dying at 1229_SoPW.pl line 23, <> line 1. a MyCarp::croak("croaking") called at 1229_SoPW.pl line 22 MyModule::a("MyModule") called at 1229_SoPW.pl line 30 b dying at 1229_SoPW.pl line 23, <> line 3. Terminating on signal SIGINT(2) 17:22 >

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Beautiful, Athanasius. Thank you!