开发者

How can I get structured exceptions from Moose?

开发者 https://www.devze.com 2022-12-20 00:35 出处:网络
Consider this simple class: package Foo; use Moose; has foo => ( is => \'rw\', isa => \'Int\' );

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 w开发者_Python百科ould 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.


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


Check out MooseX::Throwable, which replaces the error_class value in the metaclass. The code looks a little old however (metaroles do support error class roles now), but the current method looks like it will still work.


I had the same question about a year ago and asked at the #moose IRC channel. The answer was that Moose doesn't really support structured exceptions.... yet.

There is a general agreement that it is a shortcoming of Moose that should be fixed, but the task of introducing exceptions everywhere is tedious and hasn't (afaik) been carried out yet.

The approach in MooseX::Error::Exception::Class is very brittle, since it is based on parsing the messages from Moose.

Since you can't really get reliable structured exceptions from Moose, consider using introspection to test each of your type constraints one by one when setting a new value. Some times this is a feasible approach.

Btw: note that there is a nasty bug in the way Moose handles composite constraints.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号