处理Zend Framework的Controller插件中抛出的异常

Jak*_*e N 5 php plugins zend-framework exception-handling

我有一个扩展的Acl插件Zend_Controller_Plugin_Abstract,这个插件处理我所有的Acl代码.

我想在这个插件中抛出一个Exception,例如Exception_Unauthorised,然后在我的处理中ErrorController,这样我就可以为不同的应用程序使用相同的Acl插件,并使用它ErrorController来处理每个应用程序中的每个情况 - 如果需要的话.

问题是在插件中抛出异常并不会阻止原始Action执行.所以我最终得到了原始的Action输出和ErrorController输出.

如何在插件中抛出异常以阻止原始Action发生?

情况1

// This throws the `Exception_NoPermissions`, but it does not get caught by
// `ErrorController`
public function preDispatch(Zend_Controller_Request_Abstract $request)
{       
    parent::preDispatch($request);
    throw new Exception_NoPermissions("incorrect permissions");
}
Run Code Online (Sandbox Code Playgroud)

案例2

// This behaves as expected and allows me to catch my Exception
public function preDispatch(Zend_Controller_Request_Abstract $request)
{       
    parent::preDispatch($request);
    try
    {
        throw new Exception_NoPermissions("incorrect permissions");
    }
    catch(Exception_NoPermissions $e)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

案例3

我认为这是问题所在,通过更改控制器.

public function preDispatch(Zend_Controller_Request_Abstract $request)
{       
    parent::preDispatch($request);

    // Attempt to log in the user

    // Check user against ACL

    if(!$loggedIn || !$access)
    {
        // set controller to login, doing this displays the ErrorController output and
        // the login controller
        $request->getControllerName("login");
    }
}
Run Code Online (Sandbox Code Playgroud)

Jan*_*nen 4

我在 #zftalk IRC 频道上对此进行了简短的讨论,Ryan Mauger / Bittarman 表示,目前如果插件中发生异常,您需要手动重定向用户。

我还有一个想法,也许您可​​以使用单独的插件来检查异常。如果您查看 ErrorHandler 插件,它会检查请求是否包含异常并对其进行操作。

问题是ErrorHandler 在routeShutdown 上触发,例如。当请求已经完成时。如果您创建了一个查看异常的自定义插件,但在 preDispatch 上运行,则可能会自动执行此任务。

请注意,您需要确保此自定义插件在任何可能引发异常的插件之后运行。