php - 如何使用骨架项目 'Application' 模块中的错误处理程序来捕获事件回调中的错误?

标签 php error-handling zend-framework2

我正在尝试将回调附加到 ZF2 事件管理器中的"dispatch"事件,以自动对每个请求进行身份验证。

// Auth/Module.php
class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager = $e->getApplication()->getEventManager();

        $eventManager->attach(
            MvcEvent::EVENT_DISPATCH,
            array($this, 'authCallback')
        );

        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

    public function authCallback(MvcEvent $event)
    {
        // SNIP

        if (! $authenticated) {
            throw new UnauthorizedException('Yada yada');
        }
    }

如果身份验证失败,我会抛出一个异常,我想使用 skeleton-project Application module 中内置的错误处理来处理这个问题。 .我遇到的问题是它似乎正在处理 Controller 中抛出的错误,但不会处理回调中的身份验证服务抛出的异常('dispatch'事件 Hook )

我尝试将回调附加到不同的事件,例如“完成”或“渲染”,并尝试在附加事件时更改优先级,但没有任何效果。如何使用现有的错误处理程序捕获此异常?

我还尝试像这样在回调中的事件上设置错误
    public function authCallback(MvcEvent $event)
    {
        $auth = \Zend_Auth::getInstance();

        // SNIP
        if (! $authenticated) {
            $event->setError('somethings wrong');
        }
    }

但是当我这样做时,没有处理任何错误,并且原始请求无论如何都会通过。

最佳答案

我最终不得不在事件上设置错误和异常,然后触发 EVENT_DISPATCH_ERROR 而不是仅仅抛出异常。

public function authCallback(MvcEvent $event)
{
    $auth = \Zend_Auth::getInstance();

    // SNIP
    if (! $authenticated) {
        $event->setError('Something happened')
            ->setParam(
                'exception',
                new UnauthorizedException('blah blah')
            );

        $event->getApplication()
            ->getEventManager()
            ->trigger(
                MvcEvent::EVENT_DISPATCH_ERROR,
                $this,
                $event
            );
    }
}

关于php - 如何使用骨架项目 'Application' 模块中的错误处理程序来捕获事件回调中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24620950/

相关文章:

php - 在数据库中保留 1 周数据

php - Yii2:无法执行应用程序。 Apache 显示 "Index of"

PHP 代码显示在 HTML 代码之后

bash - Vps无法登录

php - 访问 Zend Framework 2 中的模块配置

php - 在 codeigniter 中设置基本 url

php - 如果 XML 文件为空,则捕获 PHP 错误

error-handling - 纯Fortran过程中的I/O

php - ZF2维护页面

php - 如何按照 Apigility 方式验证嵌套数据?