How can i simulate a 404 error with Symfony2?

Rachid O picture Rachid O · Dec 31, 2012 · Viewed 48k times · Source

so i'm looking for a way to simulate an 404 error, i tried this :

throw $this->createNotFoundException();  

and this

return new Response("",404);

but none does work.

Answer

René Höhle picture René Höhle · Dec 31, 2012

You can find the solution in the Symfony2 documentation:

http://symfony.com/doc/2.0/book/controller.html

Managing Errors and 404 Pages

public function indexAction()
{
    // retrieve the object from database
    $product = ...;
    if (!$product) {
        throw $this->createNotFoundException('The product does not exist');
    }

    return $this->render(...);
}

There is a short information in the documentation:

"The createNotFoundException() method creates a special NotFoundHttpException object, which ultimately triggers a 404 HTTP response inside Symfony."

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException

In my scripts i've made it like this:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException

/**
 * @Route("/{urlSlug}", name="test_member")
 * @Template()
 */
public function showAction($urlSlug) {
    $test = $this->getDoctrine()->.....

    if(!$test) {
        throw new NotFoundHttpException('Sorry not existing!');
    }

    return array(
        'test' => $test
    );
}