summaryrefslogtreecommitdiff
path: root/lib/Moose/Manual/Exceptions.pod
blob: 61435a222f4afae6f852f0fdcdd368ea52e6d207 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# PODNAME: Moose::Manual::Exceptions
# ABSTRACT: Moose's exceptions

__END__

=pod

=encoding UTF-8

=head1 NAME

Moose::Manual::Exceptions - Moose's exceptions

=head1 VERSION

version 2.1405

=head1 EXCEPTIONS IN MOOSE

Moose will throw an exception for all error conditions. This applies both to
code in the Moose core I<as well> as to all code generated when a class is
made immutable. All exceptions are subclasses of the C<Moose::Exception>
class.

Each type of error has its own unique subclass, and many subclasses have
additional attributes to provide more information about the error's context,
such as what classes or roles were involved.

=head1 EXCEPTION STRINGIFICATION

By default, Moose exceptions remove Moose internals from the stack trace. If
you set the C<MOOSE_FULL_EXCEPTION> environment variable to a true value, then
the Moose internals will be included in the trace.

=head1 HANDLING MOOSE EXCEPTIONS

Because Moose's exceptions use the standard C<die> mechanism, you are free to
catch and handle errors however you like. You could use an C<eval> block to
catch Moose exceptions. However, the Moose team strongly recommends using
L<Try::Tiny> instead. Please refer to L<Try::Tiny>'s documentation for a
discussion of how C<eval> is dangerous.

The following example demonstrates how to catch and inspect a
L<Moose::Exception>. For the sake of simplicity, we will cause a very simple
error. The C<extends> keywords expects a list of superclass names. If we pass
no superclass names, Moose will throw an instance of
L<Moose::Exception::ExtendsMissingArgs>.

=head2 Catching with Try::Tiny

    use warnings;
    use strict;
    use Try::Tiny;

    try {
        package Example::Exception;
        use Moose;
        extends;    # <-- error!
    }
    catch {
        # $_ contains the instance of the exception thrown by the above try
        # block, but $_ may get clobbered, so we should copy its value to
        # another variable.
        my $e = $_;

        # Exception objects are not ubiquitous in Perl, so we must check
        # whether $e is blessed. We also need to ensure that $e is actually
        # the kind of exception we were expecting.
        if ( blessed $e
            && $e->isa('Moose::Exception::ExtendsMissingArgs') ) {

            my $class_name = $e->class_name;
            warn "You forgot to specify a superclass for $class_name, silly!";
        }

        # It's either another type of an object or not an object at all.
        else {
            warn "$e\n";
        }
    }

=head2 Example of catching ValidationFailedForTypeConstraint

    use warnings;
    use strict;

    use Try::Tiny;

    {
        package Person;
        use Moose;
        use Moose::Util::TypeConstraints;

        subtype 'NameStr',
            as 'Str',
            where { $_ =~ /^[a-zA-Z]+$/; };

        has age => (
            is       => 'ro',
            isa      => 'Int',
            required => 1
        );

        has name => (
            is       => 'ro',
            isa      => 'NameStr',
            required => 1
        );
    }

    my $person;
    while ( !$person ) {
        try {
            print 'Enter your age : ';
            my $age = <STDIN>;
            chomp $age;
            print 'Enter your name : ';
            my $name = <STDIN>;
            chomp $name;
            $person = Person->new(
                age  => $age,
                name => $name
            );
            my $person_name = $person->name;
            my $person_age  = $person->age;
            print "$person_name is $person_age years old\n";
        }
        catch {
            my $e = $_;

            if (
                blessed $e
                && $e->isa(
                    'Moose::Exception::ValidationFailedForTypeConstraint')
                ) {

                my $attribute_name = $e->attribute->name;
                my $type_name      = $e->type->name;
                my $value          = $e->value;

                warn
                    "You entered $value for $attribute_name, which is not a $type_name!";
            }
            else {
                warn "$e\n";
            }
        }
    }

=head2 Example of catching AttributeIsRequired

    use warnings;
    use strict;
    use Try::Tiny;

    {
        package Example::RequiredAttribute;
        use Moose;

        has required_attribute => (
            is       => 'ro',
            isa      => 'Int',
            required => 1
        );
    }

    try {
        # we're not passing required_attribute, so it'll throw an exception
        my $object = Example::RequiredAttribute->new();
    }
    catch {
        my $e = $_;
        if ( blessed $e && $e->isa('Moose::Exception::AttributeIsRequired') )
        {
            warn $e->message, "\n";
        }
        else {
            warn "$e\n";
        }
    };

=head1 MOOSE EXCEPTION CLASSES

All the exception classes are listed in L<Moose::Manual::Exceptions::Manifest>.

=head1 AUTHORS

=over 4

=item *

Stevan Little <stevan.little@iinteractive.com>

=item *

Dave Rolsky <autarch@urth.org>

=item *

Jesse Luehrs <doy@tozt.net>

=item *

Shawn M Moore <code@sartak.org>

=item *

יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>

=item *

Karen Etheridge <ether@cpan.org>

=item *

Florian Ragwitz <rafl@debian.org>

=item *

Hans Dieter Pearcey <hdp@weftsoar.net>

=item *

Chris Prather <chris@prather.org>

=item *

Matt S Trout <mst@shadowcat.co.uk>

=back

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2006 by Infinity Interactive, Inc..

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut