代码之家  ›  专栏  ›  技术社区  ›  Jake N

处理Zend框架的控制器插件中抛出的异常

  •  5
  • Jake N  · 技术社区  · 14 年前

    我有一个Acl插件 Zend_Controller_Plugin_Abstract

    我想在这个插件中抛出一个异常,例如 Exception_Unauthorised 然后在我的房间里处理这个 ErrorController ,这样我就可以对不同的应用程序使用相同的Acl插件,并使用 误差控制器 以不同的方式处理每个应用程序中的每种情况-如果需要的话。

    问题是在插件中抛出异常并不能阻止原始操作的执行。所以我最终得到了原始动作的输出和 误差控制器

    如何在插件中引发异常以阻止原始操作的发生?

    案例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");
    }
    

    案例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)
        {
    
        }
    }
    

    案例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");
        }
    }
    
    4 回复  |  直到 14 年前
        1
  •  4
  •   Jani Hartikainen    14 年前

    我在#zftalk IRC频道上快速聊了一下,Ryan Mauger/Bittarman说,如果插件中发生异常,目前需要手动重定向用户。

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

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

        3
  •  0
  •   takeshin    14 年前

    这应该管用。这完全取决于何时何地抛出异常。看看这篇博文:

    Handling errors in Zend Framework | CodeUtopia - The blog of Jani Hartikainen

        4
  •  0
  •   Layke    11 年前

    我就是这么做的。

    // Get Request Object...
    $request = $this->getRequest();
    // Do manual redirect.. select your own action...
    $this->getRequest()->setControllerName('error')->setActionName('could-not-find-destination')->setDispatched(true);
    $error = new Zend_Controller_Plugin_ErrorHandler();
    $error->type = Zend_Controller_Plugin_ErrorHandler::EXCEPTION_OTHER;
    $error->request = clone( $request );
    $error->exception = $e; // If you have caught the exception to $e, set it. 
    $request->setParam('error_handler', $error);