Michael Ekoka
Michael Ekoka

Reputation: 20078

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?

Upvotes: 27

Views: 29228

Answers (3)

crash
crash

Reputation: 670

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.

Upvotes: 1

user2406735
user2406735

Reputation: 245

You can do it like this:

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

Upvotes: 3

Vaidas Zilionis
Vaidas Zilionis

Reputation: 931

You can do like this:

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

or

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

Upvotes: 74

Related Questions