考虑这个简单的类:
package Foo;
use Moose;
has foo => ( is => 'rw', isa => 'Int' );
然后这段代码:
use Try::Tiny;
use Foo;
my $f = try {
Foo->new( foo => 'Not an Int' );
}
catch {
warn $_;
};
代码以关于类型约束失败的大错误消息而终止。
我希望能够提取失败的属性(foo
)、原因是什么(失败的类型约束)以及传递的值是(Not an Int
),而无需解析错误字符串来获取信息。
像这样的东西:
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 $_;
}
};
这可能吗?有没有一个 MooseX 发行版可以做到这一点?更好的是,是否有一些我错过的 Moose 功能可以使这成为可能?
更新:我对类型约束特别感兴趣,但其他 Moose 错误也会非常好。我也知道我可以用die
. 因此,在我编写的代码中构造异常相对容易。