Search code examples
perlmoose

Why does this attempt to customize a type constraint error message fail?


The following construct creates a type constraint that functions as expected (checks for the "Roles::Thing" role when an attribute is set) When an attribute is rejected due to not passing the constraint I would expect the custom error message "Not a thing" to appear; however the default error message is still being given. What am I doing wrong?

role_type 'DoesThing', {
   role => 'Roles::Thing',
   message => sub { "Not a thing." }
};

Update: I did not provide enough context in the original post. The way I am trying to use the new type is:

has things => (
  isa => 'ArrayRef[DoesThing]'
);

The type validation does work as expected; however I still get the default error message. My custom "Not a thing" error message is not propagated as I would have expected it to be.


Solution

  • The error message is what you get for an ArrayRef type, regardless of what you're expecting inside it.

    To get a custom error message you'll need to incorporate ArrayRef into your type declaration:

    subtype 'ArrayOfThings', 
        as 'ArrayRef[Roles::Thing]', 
        message { 'Not an array of things' };