47

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.

0

1 Answer 1

94

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
    );
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1 because you throw and not return the exception. Saved me some trouble.
NO! It will not work with return, because that is not a valid Response Object. throw it and live happily after.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.