返回 404(未找到)頁面

有時你希望返回 404(未找到)響應,因為請求的資源不存在。Symfony 允許你通過投擲 NotFoundHttpException 這樣做。

Symfony 基本控制器公開了一個 createNotFoundException 方法,它為你建立了一個例外:

public function indexAction()
{
    // retrieve the object from database
    $product = ...;

    if (!$product) {
        throw $this->createNotFoundException('The product does not exist');
    }

    // continue with the normal flow if no exception is thrown
    return $this->render(...);
}