Skip to content

Instantly share code, notes, and snippets.

@Woody2143
Created October 16, 2012 14:07
Show Gist options
  • Save Woody2143/3899480 to your computer and use it in GitHub Desktop.
Save Woody2143/3899480 to your computer and use it in GitHub Desktop.
Moose Customer Error on Type Constraint Violation
package Index;
use Mouse;
use namespace::autoclean;
use Index::Types;
has 'date' => (
is => 'rw',
isa => 'Index::Types::Date',
coerce => 1,
required => 1,
);
__PACKAGE__->meta->make_immutable();
1;
$ perl -Ilib test.pl
Attribute (date) does not pass the type constraint because: This date (2012) is not a valid date! at /opt/perlbrew/perls/cdrtools/lib/site_perl/5.14.2/x86_64-linux/Mouse/Util.pm line 361
Mouse::Util::throw_error('Mouse::Meta::Attribute=HASH(0x106bce28)', 'Attribute (date) does not pass the type constraint because: T...', 'data', 2012, 'depth', -1) called at test.pl line 6
#!/usr/bin/env perl
use Modern::Perl;
use Index;
my $index = Index->new( date => '2012' );
package Index::Types;
use Mouse::Util::TypeConstraints;
subtype 'Index::Types::Date'
=> as 'Str'
=> where { m/\d{8}/ }
=> message { "This date ($_) is not a valid date!"};
coerce 'Index::Types::Date',
from 'Str',
via {
my $digits = $_;
$digits =~ s/[^\d]//g; # Strip anything that isn't a digit.
return $digits;
};
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment