Commit | Line | Data |
45595850 |
1 | package SQL::Translator::Role::Error; |
4e43db0d |
2 | |
3 | =head1 NAME |
4 | |
5 | SQL::Translator::Role::Error - Error setter/getter for objects and classes |
6 | |
7 | =head1 SYNOPSIS |
8 | |
9 | In the class consuming the role: |
10 | |
11 | package Foo; |
12 | use Moo; |
13 | with qw(SQL::Translator::Role::Error); |
14 | |
15 | sub foo { |
16 | ... |
17 | return $self->error("Something failed") |
18 | unless $some_condition; |
19 | ... |
20 | } |
21 | |
22 | In code using the class: |
23 | |
24 | Foo->foo or die Foo->error; |
25 | # or |
26 | $foo->foo or die $foo->error; |
27 | |
28 | =head1 DESCRIPTION |
29 | |
30 | This L<Moo::Role> provides a method for getting and setting error on a |
31 | class or object. |
32 | |
33 | =cut |
34 | |
5f7fd749 |
35 | use Moo::Role; |
68d75205 |
36 | use Sub::Quote qw(quote_sub); |
5f7fd749 |
37 | |
d24c55fe |
38 | has _ERROR => ( |
39 | is => 'rw', |
40 | accessor => 'error', |
41 | init_arg => undef, |
68d75205 |
42 | default => quote_sub(q{ '' }), |
d24c55fe |
43 | ); |
5f7fd749 |
44 | |
4e43db0d |
45 | =head1 METHODS |
46 | |
47 | =head2 $object_or_class->error([$message]) |
48 | |
49 | If called with an argument, sets the error message and returns undef, |
50 | otherwise returns the message. |
51 | |
52 | As an implementation detail, for compatibility with L<Class::Base>, the |
53 | message is stored in C<< $object->{_ERROR} >> or C<< $Class::ERROR >>, |
54 | depending on whether the invocant is an object. |
55 | |
56 | =cut |
57 | |
5f7fd749 |
58 | around error => sub { |
59 | my ($orig, $self) = (shift, shift); |
60 | |
45287c81 |
61 | # Emulate horrible Class::Base API |
d24c55fe |
62 | unless (ref($self)) { |
63 | my $errref = do { no strict 'refs'; \${"${self}::ERROR"} }; |
45287c81 |
64 | return $$errref unless @_; |
65 | $$errref = $_[0]; |
66 | return undef; |
67 | } |
68 | |
5f7fd749 |
69 | return $self->$orig unless @_; |
45287c81 |
70 | $self->$orig(@_); |
5f7fd749 |
71 | return undef; |
72 | }; |
73 | |
4e43db0d |
74 | =head1 SEE ALSO |
75 | |
76 | =over |
77 | |
78 | =item * |
79 | |
80 | L<Class::Base/Error Handling> |
81 | |
82 | =back |
83 | |
84 | =cut |
85 | |
5f7fd749 |
86 | 1; |