[Catalyst-dev] A suggestion(or question) about exception handling.
Kee Hinckley
nazgul at somewhere.com
Wed Jul 23 16:59:22 BST 2008
On Jul 21, 2008, at 5:46 PM, Matt S Trout wrote:
> On Sat, Jul 19, 2008 at 10:16:55PM -0400, Chae Lee wrote:
>> hi all,
>>
>> in my Catalyst application, I'm using my own exception handling
>> based on
>> "Error.pm", and used to ask myself what if Catalyst provided the
>> facility.
>>
>> I know there are several ways in error(or exception) handling in
>> Perl, but,
>> anyway my favorite is "try/catch."
>>
>> today I saw Catalyst::Exception. It wasn't what I expected.
>>
>> so... is there already any extension based on Error.pm in Catalyst
>> OR any
>> plan??
>
> Extension for what?
>
> There's nothing to stop you using Error.pm in the Catalyst app - I
> don't
> really see what Catalyst needs to do about it?
I use Error extensively in Catalyst, but I understand the problem he
raises. Right now Catalyst traps errors itself Catalyst::execute().
What Chae Lee probably wants (I know I do) is a way to insert an Error
handler that traps those errors, or at the very least, uses try/catch
so that what gets stored in $c->error are Error objects instead of
strings. You can't fix this with a Plugin because you have no way of
knowing when in the process your plugin will be called. As a result,
I tend to end up with actions that look like:
sub send_tweet : Local {
my ($self, $c) = @_;
try {
...
} otherwise {
push(@errors, shift);
};
return $c->cleanup(\@errors);
}
And "cleanup" is a method I added (see below), that gathers up any
Catalyst errors that are hanging around, and optionally sets the
template to an error template.
Then finally in my View I gather up what's there, convert them all to
Error objects, and deal with displaying them if appropriate. It's not
the cleanest solution in the world.
=item cleanup($errors, [$error_template], [$good_template])
Call this at the end of any Component that needs to handle any
errors. It will
consolidate any Catalyst errors with those passed in, store them in
the stash,
and clear the Catalyst errors. It will return 1 if there are no
errors, 0 if
there are errors, so it can be safely used as the return value from
Controller
Actions.
The optional template arguments will be set as appropriate if passed.
=cut
sub cleanup {
my $c = shift;
my ($errors, $error_template, $good_template) = @_;
# store any that are hanging around
unshift(@$errors, @{ $c->error() });
if (@$errors) {
push(@{ $c->stash->{Errors} }, @$errors);
$c->clear_errors();
$c->template($error_template) if ($error_template);
@$errors = ();
return 0;
} else {
$c->template($good_template) if ($good_template);
return 1;
}
}
More information about the Catalyst-dev
mailing list