From: Shawn M Moore Date: Fri, 15 Jun 2012 19:31:42 +0000 (-0500) Subject: Basic type exceptions X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=606ada8f7a84130022808ea4d88749680bb7dffd;p=gitmo%2FMoose.git Basic type exceptions --- diff --git a/lib/Moose/Meta/TypeConstraint.pm b/lib/Moose/Meta/TypeConstraint.pm index 206a0a6..974d59d 100644 --- a/lib/Moose/Meta/TypeConstraint.pm +++ b/lib/Moose/Meta/TypeConstraint.pm @@ -16,6 +16,7 @@ use Eval::Closure; use Scalar::Util qw(blessed refaddr); use Sub::Name qw(subname); use Try::Tiny; +use Moose::Util (); use base qw(Class::MOP::Object); @@ -235,8 +236,12 @@ sub assert_valid { my $error = $self->validate($value); return 1 if ! defined $error; - require Moose; - Moose->throw_error($error); + Moose::Util::throw( + message => $error, + class => 'Moose::Exception::TypeConstraint', + type_name => $self->name, + value => $value, + ); } sub get_message { diff --git a/t/exceptions/attribute_types.t b/t/exceptions/attribute_types.t new file mode 100644 index 0000000..4de5200 --- /dev/null +++ b/t/exceptions/attribute_types.t @@ -0,0 +1,42 @@ +#!/usr/bin/perl + +use strict; +use warnings; + +use Test::More; +use Test::Fatal; +use Moose::Util::TypeConstraints; + +BEGIN { + package Foo; + use Moose; + + has count => ( + is => 'rw', + isa => 'Int', + ); +} + +my $exception = exception { Foo->new(count => "test") }; +isa_ok($exception, 'Moose::Exception::TypeConstraint'); +is($exception->message, q{Attribute (count) does not pass the type constraint because: Validation failed for 'Int' with value "test"}, 'exception->message'); +is($exception->value, "test", 'exception->value'); +is($exception->type_name, "Int", 'exception->type_name'); +is($exception->attribute_name, "count", 'exception->attribute_name'); + +my $value = []; +$exception = exception { Foo->new->count($value) }; +isa_ok($exception, 'Moose::Exception::TypeConstraint'); +is($exception->message, q{Attribute (count) does not pass the type constraint because: Validation failed for 'Int' with value [ ]}, 'exception->message'); +is($exception->value, $value, 'exception->value'); +is($exception->type_name, "Int", 'exception->type_name'); +is($exception->attribute_name, "count", 'exception->attribute_name'); + +$exception = exception { find_type_constraint('Int')->assert_valid("eek") }; +isa_ok($exception, 'Moose::Exception::TypeConstraint'); +is($exception->message, q{Validation failed for 'Int' with value "eek"}, 'exception->message'); +is($exception->value, "eek", 'exception->value'); +is($exception->type_name, "Int", 'exception->type_name'); +is($exception->attribute_name, undef, 'exception->attribute_name'); + +done_testing;