Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i simulate a 404 error with Symfony2? [duplicate]

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.

like image 240
Rachid O Avatar asked Dec 31 '12 16:12

Rachid O


1 Answers

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
    );
}
like image 178
René Höhle Avatar answered Oct 18 '22 14:10

René Höhle