返回 404 回覆

當在伺服器上找不到資源時返回 404 響應,在 Symfony 中,可以通過丟擲 NotFoundHttpException 異常來建立此狀態。為避免控制器內部的額外 use 語句,請使用 Controller 類提供的 createNotFoundException()

<?php

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));
    }

}