Tweaking what Moose does when a type constraint fails

Back when Curtis Poe was at Booking.com we were in the the first team to use Moose (actually Mouse at the time) for anything serious. While it saved us a lot of time overall that we'd otherwise have spend on writing boilerplate code we found the Moose support for type constraints to be fairly inflexible for our purposes.

Moose will simple die if you pass it a value that violates a type constraint, in an environment where you control the whole stack this is usually what you want, but when you're dealing with data from other people and user-supplied parameters you often want to handle the situation more gracefully.

Curtis pointed this out on the Moose mailing list, and quickly found that this was something covered in the Moose FAQ.

I hacked up something that would change the behavior globally, but of course this is something you want to do on a per-attribute level. Jesse Luehrs provided a basic implementation of it which I expanded on, and which I've now uploaded to the CPAN as MooseX::Attribute::TypeConstraint::CustomizeFatal

The module allows you to tweak what Moose does when a type constraint fails on a per-attribute level. The default is to die as Moose does by default, but you can also make it warn and accept the bad value, or warn and fall back on the default value, or just silently ignore the bad value and fall back on the default value.

Leave a comment

About Ævar Arnfjörð Bjarmason

user-pic Blogging about anything Perl-related I get up to.