1

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

Alex Yu
  • 31
  • 6

1 Answers1

2

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.

Tim Fountain
  • 33,093
  • 5
  • 41
  • 69
  • 1
    This is the easiest way. Other options are (1.) creating a custom ErrorHandler with 404 support and throw a 404 Exception if an item is not found, or (2.) injecting the NotFoundHandler into the handler and call it directly: `$this->notFoundHandler->handle($request)`, or (3) convert it to a middleware and call `return $handler->process($request)` (which will trigger the NotFoundHandler). – xtreamwayz Jun 21 '18 at 05:35
  • or you can send it on header information: `$requestResponse = $request->withHeader('HTTP',404); return $handler->handle($requestResponse);` – rafaelphp Jul 18 '18 at 20:56