No longer need version checks
[gitmo/Moose.git] / lib / Throwable / Error.pm
CommitLineData
7f92fabb 1package Throwable::Error;
c9209d23 2use Moose;
7f92fabb 3with '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
31Throwable::Error is a base class for exceptions that will be thrown to signal
32errors and abort normal program flow. Throwable::Error is an alternative to
33L<Exception::Class|Exception::Class>, the features of which are largely
34provided by the Moose object system atop which Throwable::Error is built.
35
36Throwable::Error performs the L<Throwable|Throwable> and L<StackTrace::Auto>
37roles. That means you can call C<throw> on it to create and throw n error
38object in one call, and that every error object will have a stack trace for its
39creation.
40
41=cut
42
43use overload
44 q{""} => 'as_string',
45 fallback => 1;
46
47=attr message
48
49This attribute must be defined and must contain a string describing the error
50condition. This string will be printed at the top of the stack trace when the
51error is stringified.
52
53=cut
54
55has message => (
56 is => 'ro',
57 isa => 'Str',
58 required => 1,
59);
60
61=attr stack_trace
62
63This attribute, provided by L<StackTrace::Auto>, will contain a stack trace
64object guaranteed to respond to the C<as_string> method. For more information
65about the stack trace and associated behavior, consult the L<StackTrace::Auto>
66docs.
67
68=method as_string
69
70This method will provide a string representing the error, containing the
71error's message followed by the its stack trace.
72
73=cut
74
75sub 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
84sub 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);
98no Moose;
991;