develooper Front page | perl.moose | Postings from June 2011

Re: Moose Type Constraints violations to warnings?

Thread Previous | Thread Next
From:
Karen Etheridge
Date:
June 10, 2011 09:16
Subject:
Re: Moose Type Constraints violations to warnings?
Message ID:
20110610161611.GG164@tequila.etheridge.ca
On Fri, Jun 10, 2011 at 03:06:29AM -0700, Ovid wrote:
> When I declare a parameter as follows:
> 
> 
>     has 'some_val' => (
>         is  => 'rw',
>         isa => 'Int',
>     );
>  
> Later if I do $object->some_value("foobar"), it blows up with a stack trace because of the type constraint violation.
> 
> Without using signal handlers, is there some way I can convert that exception into a warning except when something like $ENV{HARNESS_ACTIVE} is true? Preferably on a per-attribute basis?

I see a few options:

1. Why not simply use a Str type instead of Int, if you're not absolutely sure
that the provided value is an Int?  Then you'd be able to see the value
that was passed in, even if it wasn't a number.

2. Define a Str-to-Int coercion that selected an appropriate default if
the value provided wasn't an int.  You could also log a warning whenever
the coercion is run, to catch these issues in testing.

3. Alternatively, you could wrap your calls to setters and constructors with a
try/catch block using your exception handling package of choice (I
recommend Try::Tiny). You'd have to examine the stack trace you get back to
see what type of problem occured, and then replace the bad value with a
better one.  MooseX::Constructor::AllErrors can make this easier, but
that's a Moose, not Mouse, solution.

Given the context you've provided, I'd lean towards #2.


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About