2012-12-31 57 views

回答

69

您可以找到Symfony2的文檔中的解決方案:

http://symfony.com/doc/2.0/book/controller.html

管理錯誤和404頁

public function indexAction() 
{ 
    // retrieve the object from database 
    $product = ...; 
    if (!$product) { 
     throw $this->createNotFoundException('The product does not exist'); 
    } 

    return $this->render(...); 
} 

有文檔在很短信息:

「createNotFoundException()方法創建一個特殊的NotFoundHttpException對象,最終觸發Symfony中的404 HTTP響應。「

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException 

在我的劇本我做了這樣的:

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

+1,因爲你'throw'而不是'return'例外。爲我節省了一些麻煩。 – ferdynator

+3

不!它不會與'return'一起工作,因爲這不是一個有效的'Response'對象。拋出它後幸福地生活。 – ferdynator