symfony2 Routing Return a 404 response


404 responses are returned when a resource is not found on the server, in Symfony this status can be created by throwing a NotFoundHttpException exception. To avoid an extra use statement inside a controller use the createNotFoundException() provided by the Controller class


namespace Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class TestController extends Controller
     * @Route("/{id}", name="test")
     * Recommended to avoid template() as it has a lot of background processing.
     * Query database for 'test' record with 'id' using param converters.
    public function testAction(Test $test)
        if (!$test) {
            throw $this->createNotFoundException('Test record not found.');
        return $this->render('::Test/test.html.twig', array('test' => $test));