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?
You can do like this:
$this->getResponse()->setHttpResponseCode(404);
or
throw new Zend_Controller_Action_Exception('This page does not exist', 404);
You can do it like this:
$this->getResponse()->setHttpResponseCode(404);
return;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With