Skip to content

Instantly share code, notes, and snippets.

@jberger
Created March 18, 2018 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jberger/f73d93444e6c8c4d507d3abcd30302b1 to your computer and use it in GitHub Desktop.
Save jberger/f73d93444e6c8c4d507d3abcd30302b1 to your computer and use it in GitHub Desktop.
package Mojo::Callback;
use Mojo::Base -strict;
use Exporter 'import';
use Sub::Util 'set_subname';
use Data::GUID;
use Mojo::Exception;
our @EXPORT = ('callback');
our @EXPORT_OK = (qw/exception stack/);
our $STACK = [];
our $LOGGER;
our $TAGS = {};
sub callback (&) {
my $cb = shift;
my $logger = $LOGGER;
my $tags = $TAGS;
my $stack = stack();
my $name = 'Mojo::Callback::__ANON__::' . Data::GUID->guid_string;
set_subname $name, $cb;
return sub {
local $LOGGER = $logger;
local $TAGS = $tags;
local $STACK = $stack;
$cb->(@_);
};
}
sub exception {
Mojo::Exception->new(@_ == 1 ? (message => shift) : @_)->frames(stack(2));
}
sub stack {
my $start = shift // 1;
my @frames;
while (my @trace = caller($start++)) {
last if $trace[3] =~ /\QMojo::Callback::__ANON__::/;
push @frames, \@trace;
}
return [@frames, @$STACK];
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment