Hi krautcat, there are no silly questions, only silly answers ;-)
yes, in this case "an exception" means that the program exits with a fatal error returned by the type checking sub if the value is not valid. When it dies it "throws an exception".
Now, as to your other question. Yes, you can use the Types to validate elsewhere. You should spend some time reading in the docs of Type::Tiny and friends (which is spread through several files).
One of the simplest ways is to make use of the auto-defined is_<type_name>() functions that Type::Tiny defines and provides in Types::Standard:
Package:
package Krautcat;
use strict; use warnings;
use Moo;
use MooX::TypeTiny;:
use Types::Standard qw/ Str is_Str /;
has foo => ( is => 'ro', isa => Str, required => 1 );
has baz => ( is => 'rw', );
sub qux {
my $self = shift;
my $val = shift;
die 'not a string' if not is_Str $val;
$self->baz( $val );
return { baz => $self->baz };
}
1;
Script:
use strict; use warnings;
use Test::Most;
use_ok 'Krautcat', 'Loaded class';
throws_ok(
sub { my $obj = Krautcat->new() },
qr/Missing required arguments: foo/,
'empty params throws ok',
);
dies_ok(
sub { my $obj = Krautcat->new( foo => [42] ) },
'non-string param for constructor dies ok',
);
like(
$@,
qr/\QReference [42] did not pass type constraint "Str"\E/,
'assertion failure message looks ok',
);
my $obj = new_ok(
'Krautcat' => [ foo => 'bar' ],
'obj with valid constructor params',
);
is( $obj->foo, 'bar', 'attr has correct val from constructor' );
throws_ok(
sub { $obj->qux( [42] ) },
qr/not a string/,
'non-string param for qux() throws ok',
);
lives_and(
sub { is_deeply $obj->qux('blorg'), { baz => 'blorg' } },
'string param for qux() validates ok',
);
done_testing;
Output:
prove -v 1199413.pl
1199413.pl ..
ok 1 - use Krautcat;
ok 2 - empty params throws ok
ok 3 - non-string param for constructor dies ok
ok 4 - assertion failure message looks ok
ok 5 - 'obj with valid constructor params' isa 'Krautcat'
ok 6 - attr has correct val from constructor
ok 7 - non-string param for qux() throws ok
ok 8 - string param for qux() validates ok
1..8
ok
All tests successful.
Files=1, Tests=8, 0 wallclock secs ( 0.01 usr 0.01 sys + 0.08 cusr
+ 0.01 csys = 0.11 CPU)
Result: PASS
This is the most simple feature and example I can think of; there is a lot more to discover!
The way forward always starts with a minimal test.