Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 336
Emil Davtyan Avatar asked Mar 30 '26 02:03

Emil Davtyan


1 Answers

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 } ] } );
};
like image 139
Paul Sturm Avatar answered Apr 02 '26 18:04

Paul Sturm