2012-12-31 3 views

risposta

69

È possibile trovare la soluzione nella documentazione di Symfony2:

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

gestione degli errori e 404 pagine

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

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

C'è un breve informazioni contenute nella documentazione:

"Il metodo createNotFoundException() crea uno speciale NotFoundHttpException oggetto, che in definitiva innesca una risposta HTTP 404 all'interno di Symfony. "

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException 

Nei miei scritti ho fatto in questo modo:

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 perché si 'throw' e non' return' l'eccezione. Mi ha salvato qualche problema. – ferdynator

+3

NO! Non funzionerà con 'return', perché non è un oggetto' Response' valido. "buttalo" e vivi felicemente dopo. – ferdynator