symfony Controllers Returning a 404 (Not Found) page


Sometimes you want to return a 404 (Not Found) response, because the requested resource does not exist. Symfony allows you to do so by throwing a NotFoundHttpException.

The Symfony base Controller exposes a createNotFoundException method which creates the exception for you:

public function indexAction()
    // retrieve the object from database
    $product = ...;

    if (!$product) {
        throw $this->createNotFoundException('The product does not exist');

    // continue with the normal flow if no exception is thrown
    return $this->render(...);