Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get structured exceptions from Moose?

Tags:

perl

moose

Consider this simple class:

package Foo;
use Moose;
has foo => ( is => 'rw', isa => 'Int' );

And then this code:

use Try::Tiny;
use Foo;
my $f = try {
    Foo->new( foo => 'Not an Int' );
}
catch {
    warn $_;
};

The code dies with a nice big error message about type constraints failing.

I'd like to be able to extract what attribute failed (foo), what the reason was (failed type constraint) and what the value passed was (Not an Int) without having to parse an error string to get the info.

Something like this:

catch {
    if( $_->isa( 'MooseX::Exception::TypeConstraint' ) ) {
         my $attrib = $_->attribute;
         my $type   = $_->type;
         my $value  = $_->bad_value;

         warn "'$value' is an illegal value for '$attrib'.  It should be a $type\n"; 
    }
    else {
         warn $_;
    }
};

Is this possible? Is there a MooseX distribution that can make this happen? Better yet, is there some Moose feature that I missed that will make this possible?

Update: I am particularly interested in type constraints, but other Moose errors would be very good as well. I am also aware that I can throw objects with die. So, structuring exceptions in code I write is relatively easy.

like image 597
daotoad Avatar asked Feb 11 '10 00:02

daotoad


1 Answers

I haven't tried it myself, but I think MooseX::Error::Exception::Class might be what you're looking for.

like image 92
cjm Avatar answered Sep 20 '22 15:09

cjm