Emil Davtyan
Emil Davtyan

Reputation: 14099

Modify Exception Handling using Hooks in Dancer

I'm trying to set up a hook to catch all exceptions and errors thrown from my Dancer application ( an API ) and pass them to a function that sets the HTTP status code and returns the hash ( serialized as JSON ).

Everything works fine when I use try/catch, but when I move it to a hook it runs the code but the response is formed using the default error mechanism instead of my function.

This is the hook I'm using:

# Handle errors
hook on_handler_exception => sub {
    my $e = shift;
    debug "ON HANDLER EXCEPTION";
    return API::Exception->handle($e); # sets status code and returns hash depending on the exception
};

I also tried using halt instead of return to stop any further processing of the exception but it didn't alter anything.

How would I accomplish this with Dancer? Thanks.

Upvotes: 3

Views: 671

Answers (2)

Paul Sturm
Paul Sturm

Reputation: 21

use the "on_route_exception" hook instead ...

hook on_route_exception => sub
{
    my ( $exception ) = @_;
    error( $exception );
    status( 'error' );
    halt( { errors => [ { message => 'An unhandled exception occurred', code => 0 } ] } );
};

Upvotes: 2

smartmeta
smartmeta

Reputation: 1149

Have a look at the code of Dancer::Error.

I think something like

my $content = Dancer::Engine->engine("template")->apply_renderer($template_name, $ops);
    return Dancer::Response->new(
        status => $self->code,
        headers => ['Content-Type' => 'text/html'],
        content => $content);

from the _render_html method could help you.

Upvotes: 0

Related Questions