Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw 404 exceptions in Zend Framework

I'm trying to use the Zend_Controller_Plugin_ErrorHandler to handle my error 404 cases. According to the doc, the plugin has constants that one can use to match Exception types and handle them accordingly. 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

Does anyone know how to create exceptions of these types specifically?

like image 777
Michael Ekoka Avatar asked Sep 28 '10 18:09

Michael Ekoka


3 Answers

You can do like this:

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

or

throw new Zend_Controller_Action_Exception('This page does not exist', 404);
like image 162
Vaidas Zilionis Avatar answered Nov 15 '22 07:11

Vaidas Zilionis


You can do it like this:

$this->getResponse()->setHttpResponseCode(404);
return;
like image 25
user2406735 Avatar answered Nov 15 '22 05:11

user2406735


I always land here when googling this, so the answer for Zend Framework 2, Zend Framework 3 and also Laminas is (in case you're using the MVC module):

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

You must return inside of the action and make sure you return the response object! Otherwise it's possible that you expose more data then you want too!

If you're using Psalm and get an error, because {Laminas|Zend}\Stdlib\ResponseInterface doesn't know setStatusCode(), you must do a type check before:

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

For doing a 404 in Zend Expressive or Laminas Mezzio then please refer to the documentation.

like image 21
crash Avatar answered Nov 15 '22 07:11

crash