[dancer-users] exceptional dancing

Andrew Beverley andy at andybev.com
Thu Nov 20 18:16:09 GMT 2014


On Thu, 2014-11-20 at 13:29 +0200, WK wrote:
> So I have simple question: how and where to catch errors in Dancer
> app?

As Ovid says, there are many ways to approach the problem. This is mine.

I use Log::Report, which has the advantage of doing translations and
logging, as well as handling exceptions. For errors, it provides various
levels ("error", "warn", "info" etc).

Log::Report provides one or more dispatchers, which can be configured to
filter on the severity of the error message. A dispatcher can be a
callback, so I configure multiple dispatchers for different types of
messages.

If it's a user error then that will be displayed to the web page, and
depending on the severity I'll either allow the route to continue or
stop it there. Otherwise I'll log it to the system, which I plan to do
with errbit in the future.

Whenever I call a function in my controller, I wrap it in my own eval
equivalent:

    process(sub {...})

This function does the work, and if it's fatal (including for a user
error) it stops the route and displays the error.

    sub process
    {
        my $coderef = shift;
        try {&$coderef};
        $@->reportFatal(to => 'error_handler', is_fatal => 0);
        $@ ? 0 : 1; # Return true on success
    }

In terms of exceptions that I wasn't expecting (e.g. unable to connect
to the database), I catch all of these using the init_error hook:

    hook init_error => sub {
        my $error = shift;
        panic $error->{exception};
    };

This works, but it's a bit messy, so I'd like to find a better way of
doing it.

That's it in short. I hope to write it all up at some point and/or
create a plugin, but feel free to ask questions in the meantime.

Andy




More information about the dancer-users mailing list