如何在Zend Framework中抛出404异常

时间:2010-09-28 18:14:03

标签: php zend-framework

我正在尝试使用Zend_Controller_Plugin_ErrorHandler来处理我的错误404个案例。 根据{{​​3}},插件具有常量,可以用来匹配异常类型并相应地处理它们。 e.g。

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

有谁知道如何专门创建这些类型的例外?

3 个答案:

答案 0 :(得分:69)

你可以这样做:

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

throw new Zend_Controller_Action_Exception('This page does not exist', 404);

答案 1 :(得分:3)

你可以这样做:

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

答案 2 :(得分:0)

在搜索时,我总是会落在这里,因此Zend Framework 2,Zend Framework 3和Laminas的答案是(如果您使用的是MVC模块):

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

您必须在操作内return,并确保返回响应对象!否则,您可能会公开更多的数据!

如果您使用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 then please refer to the documentation中执行404时。