phpzend-frameworkmezzio

How to throw 404 error in a Zend Expressive?


I have a problem. I need to throw a 404 error when I do not get a $item (see code).

class HomeHandler implements RequestHandlerInterface
{
    private $template;
    private $dataService;

    public function __construct(
        Template\TemplateRendererInterface $template = null, 
        DataServiceInterface $dataService
    ) {
        $this->template = $template;
        $this->dataService = $dataService;
    }

    public function handle(ServerRequestInterface $request) : ResponseInterface
    {
        $alias = $request->getAttribute('alias', '');

        $item = $this->dataService->getItem($alias);

        if(!isset($item)) {
            // Here you need to throw 404 error
        }

        return new HtmlResponse($this->template->render('app::home-page', $item));
    }
}

I use Zend Expressive 3.

Grateful for any of your thoughts


Solution

  • You can return a HTML response with a specific status code:

    if (!$item) {
        return new HtmlResponse($this->template->render('error::404'), 404);
    }
    

    adjust the template to point at whichever is appropriate.