Re: how to handle error with type constraint
[email protected] (Stevan Little)
| Newsgroups | perl.moose |
|---|---|
| Message-ID | <[email protected]> |
Vincent,
The simplest way to do this is to catch the exception, so wrap the
object creation inside an eval { } and if you get an exception write
the info to your log file.
There is a way to alter the Moose error handling behavior, but it
would be overkill in this case where simple exception handling would
suffice.
- Stevan
On Sep 22, 2008, at 9:40 AM, vincent roudil wrote:
> Hello Moose,
> I am just starting to explore Moose. This is probably something
> simple, but
> I can't figure out the best way to do this.
>
> With the Moose type constraint, I would like to get control of the
> error
> handling when the type is invalid.
>
> Here is an example.
>
> a class host, with 2 attributes, name and ip_addr, with a control
> on the IP
> address validity:
> ##### package host.pm
> package host;
> use Moose;
> use Moose::Util::TypeConstraints;
>
> use Regexp::Common qw /net/;
> subtype IPAddr
> => as Str
> => where {/^$RE{net}{IPv4}$/}
> => message { 'invalid IP address'};
>
> has 'ip_addr' => (isa => 'IPAddr', is => 'ro', required => 1);
> has 'name' => (isa => 'Str', is => 'ro', required => 1);
> 1;
> ##### end package host.pm
>
> The type constraints works fine. Only that when the IP address is
> invalid
> the program dies, with great verbosity.
>
> I would just like when IP address is invalid, to print a message in
> a log
> file, and that the creation of the instance fails quietly, so I
> could use
> the host class like this:
>
> ##### main.pl:
> use host;
>
> my $h=host->new(name=>'jupiter', ip_addr=>'10.10.10.1');
>
> if ($h) {
> print $h->name." created successfully with the IP address ".$h-
> >ip_addr;
> }
>
> If someone could point me to the right direction, that would be great.
>
> Thanks in advance.
>
> Vincent.