27

I would like to intentionally cause a 404 error within one of the controllers in my Zend Framework application. How can I do this?

Andrew
  • 227,796
  • 193
  • 515
  • 708

2 Answers2

53

A redirect to a 404 would be:

throw new Zend_Controller_Action_Exception('Your message here', 404);

Or without Exception:

$this->_response->clearBody();
$this->_response->clearHeaders();
$this->_response->setHttpResponseCode(404);
Wouter Dorgelo
  • 11,770
  • 11
  • 62
  • 80
  • Nice, I didn't know that you could set the code for that exception. The API doc seems to point to it being for internal use only, though. – Juan Nov 15 '10 at 21:34
  • Well, I use it all the time with custom routes.. For example `example.com/:module/:controller/:random`. In the controller I check if random exists, otherwise I throw and Exception with a 404 and it works :-) – Wouter Dorgelo Nov 15 '10 at 21:36
  • Hmm, this isn't working for me. The controller keeps marching on normally. Do I need to do anything else after this? – blainarmstrong May 10 '13 at 02:13
  • can I return array as you returned string in exception? – keen Jan 08 '14 at 12:21
1

You can always set the response code manually, without throwing any exceptions.

$this->_response->clearBody();
$this->_response->clearHeaders();
$this->_response->setHttpResponseCode(404);
Juan
  • 3,433
  • 29
  • 32