代码之家  ›  专栏  ›  技术社区  ›  Michael Ekoka

如何在Zend框架中抛出404异常

  •  22
  • Michael Ekoka  · 技术社区  · 14 年前

    根据 doc ,插件有常量,可以用来匹配异常类型并相应地处理它们。例如

    switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                // 404 error -- controller or action not found
    

    2 回复  |  直到 14 年前
        1
  •  72
  •   Tim Bezhashvyly    12 年前

    你可以这样做:

     $this->getResponse()->setHttpResponseCode(404);
    

    throw new Zend_Controller_Action_Exception('This page does not exist', 404);
    
        2
  •  3
  •   smhg    4 年前

    你可以这样做:

    $this->getResponse()->setHttpResponseCode(404);
    return;
    
        3
  •  0
  •   crash    5 年前

    我总是在谷歌搜索时登陆这里,所以Zend Framework 2、Zend Framework 3和Laminas的答案是(如果您使用的是MVC模块):

    $this->response->setStatusCode(404);
    return $this->response;
    

    你必须 return 确保返回response对象 ! 否则,你可能会暴露更多的数据,然后你想!

    Psalm {Laminas|Zend}\Stdlib\ResponseInterface 我不知道 setStatusCode() ,必须先进行类型检查,然后才能执行以下操作:

     use Zend\Http\Response as HttpResponse;
     // ...
     if ($this->response instanceof HttpResponse) {
         $this->response->setStatusCode(404);
     }
     return $this->response;
    

    当你不想在Zend Expressive或Laminas Mezzio做404的时候 then please refer to the documentation .