Zend 2: How to throw a 404 error from controller

2019-04-19 06:48发布

问题:

I want to throw a '404 Page not found' error from my controller. How can I do that?

I use Zend Framework 2 not 1.

回答1:

Just try with:

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

in your controller's action method.



回答2:

class IndexController extends AbstractActionController
{
    public function previewAction ()
    {
        return $this->notFoundAction ();
    }
}


回答3:

In the correct ZF2 setup you should already have your 404 view, then in your controller action just use the following and the 404 is automatically handled for you:

   if($notTheCorrectSlugMatchOrWhatEver){
   return  $this->notFoundAction();
   }