perl - 在 Dancer 中使用 Hooks 修改异常处理

标签 perl exception-handling dancer

我试图设置一个钩子(Hook)来捕获从我的 Dancer 应用程序(一个 API)抛出的所有异常和错误,并将它们传递给一个函数,该函数设置 HTTP 状态代码并返回哈希值(序列化为 JSON)。

当我使用 try/catch 时一切正常,但是当我将它移动到钩子(Hook)时它运行代码但响应是使用默认错误机制而不是我的函数形成的。

这是我正在使用的钩子(Hook):

# 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
};

我还尝试使用 halt 而不是 return 来停止对异常的任何进一步处理,但它没有改变任何东西。

我如何使用 Dancer 完成此操作?谢谢。

最佳答案

改用“on_route_exception”钩子(Hook)......

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

关于perl - 在 Dancer 中使用 Hooks 修改异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12963195/

相关文章:

mysql - 如何将 DBIx::Simple + SQL::Abstract 与 DBIx::Connector 结合使用

exception-handling - ExceptionHandler 返回 JSON 或 XML 在 spring mvc 3 中不起作用

perl - 如何使用 Test::WWW::Mechanize::PSGI 测试 Dancer 应用程序?

mysql - 模板工具包显示唯一行

perl - 强制 Perl Dancer 使用 HTTP/1.1

perl - 在 Devel::CoverReport::DB 中,.12 和 .13 格式意味着什么?

perl - 为什么对于包含非 ASCII 字符的文件名,-e 文件存在性测试总是返回 false?

perl - 如何在 osx 上安装 perl 评论家?

c# - SQL 服务器 : Rethrow exception with the original exception number

python - try-except block : analogue for 'else' if exception was raised