perlancar has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

Since die() accepts a reference, I thought I'd use an object for a "more proper" exception system. Below is code example:

BEGIN { package Err; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(err); use overload q("") => sub { my $e = shift; "ERROR $e->[0]: $e->[1] +" }; sub new { my $class = shift; bless $_[0], $class } sub err { __PACKAGE__->new([@_]) } } package main; BEGIN { Err->import } use Carp::Always; sub f { g(); } sub g { die err(403, "Permission denied"); } f();

It prints "ERROR 403: Permission denied" as expected. However, it doesn't print stack trace even under Carp::Always. What should I do to produce stack trace?

Replies are listed 'Best First'.
Re: Die-ing with object with overloaded stringification
by blindluke (Hermit) on Sep 25, 2014 at 13:31 UTC

    You need to produce the stack trace yourself, since you are overriding the whole thing. Try:

    #!/usr/bin/perl use v5.14; use Data::Dumper; BEGIN { package Err; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(err); use overload q("") => sub { my $e = shift; "ERROR $e->[0]: $e->[1] + \n".Carp::longmess()}; sub new { my $class = shift; bless $_[0], $class } sub err { __PACKAGE__->new([@_]) } } package main; BEGIN { Err->import } use Carp; sub f { g(); } sub g { die err(403, "Permission denied"); } f();

    Which produces:

    ERROR 403: Permission denied at ./test.pl line 28. main::g() called at ./test.pl line 24 main::f() called at ./test.pl line 31

    UPDATE: I feel I should add that I don't see anything "more proper" in this way of handling stuff. Still, if you want to do it, have fun, and I hope my reply is of some use to you.

    regards,
    Luke Jefferson

      Thanks, that does the trick :)