Commit | Line | Data |
7f92fabb |
1 | package Throwable; |
c9209d23 |
2 | use Moose::Role; |
7f92fabb |
3 | # ABSTRACT: a role for classes that can be thrown |
4 | |
5 | =head1 SYNOPSIS |
6 | |
7 | package Redirect; |
8 | use Moose; |
9 | with 'Throwable'; |
10 | |
11 | has url => (is => 'ro'); |
12 | |
13 | ...then later... |
14 | |
15 | Redirect->throw({ url => $url }); |
16 | |
17 | =head1 DESCRIPTION |
18 | |
19 | Throwable is a role for classes that are meant to be thrown as exceptions to |
20 | standard program flow. It is very simple and does only two things: saves any |
21 | previous value for C<$@> and calls C<die $self>. |
22 | |
23 | =attr previous_exception |
24 | |
25 | This attribute is created automatically, and stores the value of C<$@> when the |
26 | Throwable object is created. |
27 | |
28 | =cut |
29 | |
30 | has 'previous_exception' => ( |
31 | is => 'ro', |
32 | init_arg => undef, |
33 | default => sub { |
34 | return unless defined $@ and (ref $@ or length $@); |
35 | return $@; |
36 | }, |
37 | ); |
38 | |
39 | =method throw |
40 | |
41 | Something::Throwable->throw({ attr => $value }); |
42 | |
43 | This method will call new, passing all arguments along to new, and will then |
44 | use the created object as the only argument to C<die>. |
45 | |
46 | If called on an object that does Throwable, the object will be rethrown. |
47 | |
48 | =cut |
49 | |
50 | sub throw { |
51 | my ($inv) = shift; |
52 | |
53 | if (blessed $inv) { |
54 | confess "throw called on Throwable object with arguments" if @_; |
55 | die $inv; |
56 | } |
57 | |
58 | my $throwable = $inv->new(@_); |
59 | die $throwable; |
60 | } |
61 | |
62 | no Moose::Role; |
63 | 1; |