[Dancer-users] raising exceptions in hooks.

Rusty Conover rconover at infogears.com
Tue Feb 28 05:22:06 CET 2012

Hi Everyone,

I'm trying to use a hook like:

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

hook 'database_error' => sub { 
  my $message = Carp::longmess($_[0]); 
  my $handle = shift; 
  raise DatabaseProblem => $message; 

This is documented in Dancer::Plugin::Database.

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

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:

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?

Many thanks,

InfoGears Inc.

More information about the Dancer-users mailing list