Commit | Line | Data |
7f92fabb |
1 | package Throwable::Error; |
c9209d23 |
2 | use Moose; |
7f92fabb |
3 | with 'Throwable', 'StackTrace::Auto'; |
4 | # ABSTRACT: an easy-to-use class for error objects |
5 | |
6 | =head1 SYNOPSIS |
7 | |
8 | package MyApp::Error; |
9 | use Moose; |
10 | extends 'Throwable::Error'; |
11 | |
12 | has execution_phase => ( |
13 | is => 'ro', |
14 | isa => 'MyApp::Phase', |
15 | default => 'startup', |
16 | ); |
17 | |
18 | ...and in your app... |
19 | |
20 | MyApp::Error->throw("all communications offline"); |
21 | |
22 | # or... |
23 | |
24 | MyApp::Error->throw({ |
25 | message => "all communications offline", |
26 | phase => 'shutdown', |
27 | }); |
28 | |
29 | =head1 DESCRIPTION |
30 | |
31 | Throwable::Error is a base class for exceptions that will be thrown to signal |
32 | errors and abort normal program flow. Throwable::Error is an alternative to |
33 | L<Exception::Class|Exception::Class>, the features of which are largely |
34 | provided by the Moose object system atop which Throwable::Error is built. |
35 | |
36 | Throwable::Error performs the L<Throwable|Throwable> and L<StackTrace::Auto> |
37 | roles. That means you can call C<throw> on it to create and throw n error |
38 | object in one call, and that every error object will have a stack trace for its |
39 | creation. |
40 | |
41 | =cut |
42 | |
43 | use overload |
44 | q{""} => 'as_string', |
45 | fallback => 1; |
46 | |
47 | =attr message |
48 | |
49 | This attribute must be defined and must contain a string describing the error |
50 | condition. This string will be printed at the top of the stack trace when the |
51 | error is stringified. |
52 | |
53 | =cut |
54 | |
55 | has message => ( |
56 | is => 'ro', |
57 | isa => 'Str', |
58 | required => 1, |
59 | ); |
60 | |
61 | =attr stack_trace |
62 | |
63 | This attribute, provided by L<StackTrace::Auto>, will contain a stack trace |
64 | object guaranteed to respond to the C<as_string> method. For more information |
65 | about the stack trace and associated behavior, consult the L<StackTrace::Auto> |
66 | docs. |
67 | |
68 | =method as_string |
69 | |
70 | This method will provide a string representing the error, containing the |
71 | error's message followed by the its stack trace. |
72 | |
73 | =cut |
74 | |
75 | sub as_string { |
76 | my ($self) = @_; |
77 | |
78 | my $str = $self->message; |
79 | $str .= "\n\n" . $self->stack_trace->as_string; |
80 | |
81 | return $str; |
82 | } |
83 | |
84 | sub BUILDARGS { |
85 | my ($self, @args) = @_; |
86 | |
87 | return {} unless @args; |
88 | return {} if @args == 1 and ! defined $args[0]; |
89 | |
90 | if (@args == 1 and (!ref $args[0]) and defined $args[0] and length $args[0]) { |
91 | return { message => $args[0] }; |
92 | } |
93 | |
94 | return $self->SUPER::BUILDARGS(@args); |
95 | } |
96 | |
97 | __PACKAGE__->meta->make_immutable(inline_constructor => 0); |
98 | no Moose; |
99 | 1; |