sukria/Dancer — Issue #751: exception raised in hook, caught in route
Author: dams
Created: 2012-02-29 14:06:11+00:00
State: open

I'm trying to use a hook like:

register_exception('DatabaseProblem', message_pattern => "Database problem: %s");

```perl
hook 'database_error' => sub {
my $message = Carp::longmess($_[0]);
my $handle = shift;
raise DatabaseProblem => $message;
return;
};
```
This is documented in Dancer::Plugin::Database.

To raise a DatabaseProblem exception in the event of a database error such as:

```perl
my $dbh = database();
try {
$dbh->do("insert into table_that_does_not_exist values(?)", undef, "yes");
} catch {
my ($exception) = @_;
if ($exception->does('DatabaseProblem') {
# do something
}
};
```

The problem I'm getting is:

An error occured while executing the filter named database_error:

It seems we can't raise an exception in the database_error hook or any hook really, without having it generate a 500 error because Dancer::Hook catches all exceptions thrown in hooks and halts rendering.

Relevant excerpt from Hook.pm:

```perl
my $compiled_filter = sub {
my @arguments = @_;
return if Dancer::SharedData->response->halted;

my $app = Dancer::App->current();
return unless $properties->should_run_this_app($app->name);

Dancer::Logger::core( "entering " . $hook_name . " hook" );

try { $code->(@arguments) }
catch {
my ($exception) = @_;
# exception is not a workflow continuation but a genuine error
my $err = Dancer::Error->new(
code => 500,
title => $hook_name . ' filter error',
message => "An error occured while executing the filter named $hook_name: $exception",
exception => $exception,
);
# raise a new halt exception
Dancer::halt( $err->render );
};
};
```

Can we change this so exceptions can be raised from hooks, or is there another pattern I should be using to catch DBI errors?