How can I mark a call as "unsafe" with Carp?
Asked Answered
A

2

6

I have the same problem as in Can't disable stack trace in Carp::croak() for some reason. Because every call in the stack is considered "safe", croak() prints out a full stack trace every time. I'd like to disable that for certain calls.

Here's an example:

use Carp;

sub this_may_fail {
  # Some code...
  croak "This call failed!";
}

sub regular_code {
  this_may_fail();
}

regular_code();

Both subroutines are in the same package, so this_may_fail is automatically marked as safe. Is there any way to tell Carp that this_may_fail should be considered unsafe?

Adopted answered 18/2, 2014 at 16:59 Comment(2)
Is regular_code() the only thing calling this_may_fail? If so then you could just use a regular dieDodecagon
this_may_fail gets called from several different locations, and I need to know where it was called from so I can figure out what went wrong.Adopted
N
3

It's regular_code that's considered "safe" by this_may_fail. The check is based on namespace, so to make it unsafe, you'd place this_may_fail in a different namespace.


Or write your own croaker.

perl -e'
   use Carp qw( );
   sub untrusting_croak {
      goto &Carp::croak if $Carp::Verbose;
      my @caller = caller(1);
      die(join("", @_)." at $caller[1] line $caller[2]\n");
   }

   sub f { untrusting_croak("!!!"); }    # Line 9

   f();                                  # Line 11
'
!!! at -e line 11
Noland answered 18/2, 2014 at 17:18 Comment(1)
I ended up moving some of my functions to a different namespace. Thanks for your answer.Adopted
N
3

Not especialy pretty, but, instead of this:

sub regular_code {
   ...;
   my $result = this_may_fail(@args);
}

You could use this...

sub regular_code {
   ...;
   my $result = do {
      my $sub = \&this_may_fail;
      package DUMMY; $sub->(@args)
   };
}
Newson answered 18/2, 2014 at 17:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.