2013-12-02 13 views
7

Come catturare l'eccezione nel controller e mostrare il messaggio flash in Symfony 2?Come catturare l'eccezione in symfony 2?

try{ 
    $em = $this->getDoctrine()->getManager(); 
    $em->persist($entity); 
    $em->flush(); 

    return $this->redirect($this->generateUrl('target page')); 
} catch(\Exception $e){ 
    // What to do in this part??? 
} 

return $this->render('MyTestBundle:Article:new.html.twig', array(
    'entity' => $entity, 
    'form' => $form->createView(), 
)); 

Cosa devo fare nel blocco catch?

+0

http://stackoverflow.com/questions/5689415/symfony2-controller-wont-catch-exception – Asif

+0

toString ($ e) non funziona. Mostra FatalErrorException: Errore: chiamata alla funzione non definita toString() – Swass

+0

'echo (stringa) $ e;' o meglio, inviare una e-mail su un sito produttivo: 'mail ('[email protected] ',' Eccezione in script ... ', var_export ($ e, true)); ' – DanFromGermany

risposta

13

Si dovrebbe prestare attenzione per le eccezioni che potrebbero essere sollevate :

public function postAction(Request $request) 
{ 
    // ... 

    try{ 
    $em = $this->getDoctrine()->getManager(); 
    $em->persist($entity); 
    $em->flush(); 

    return $this->redirect($this->generateUrl('target page')); 

    } catch(\Doctrine\ORM\ORMException $e){ 
    // flash msg 
    $this->get('session')->getFlashBag()->add('error', 'Your custom message'); 
    // or some shortcut that need to be implemented 
    // $this->addFlash('error', 'Custom message'); 

    // error logging - need customization 
    $this->get('logger')->error($e->getMessage()); 
    //$this->get('logger')->error($e->getTraceAsString()); 
    // or some shortcut that need to be implemented 
    // $this->logError($e); 

    // some redirection e. g. to referer 
    return $this->redirect($request->headers->get('referer')); 
    } catch(\Exception $e){ 
    // other exceptions 
    // flash 
    // logger 
    // redirection 
    } 

    return $this->render('MyTestBundle:Article:new.html.twig', array(
    'entity' => $entity, 
    'form' => $form->createView(), 
)); 
} 
+0

' getRequest' è Deprecato da 'Symfony 2.4' e Rimosso da' Symfony 3.0'. Si prega di prendere in considerazione alcune modifiche – Trix

+0

Thx, ho aggiornato il mio post. –

3

Leggilo attentamente, le eccezioni di cattura e la generazione di un'uscita nel ramoscello sono chiaramente descritte qui. :)

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

ulteriormente,

è possibile utilizzare questo metodo primitivo per ottenere metodi di una classe:

print_r(get_class_methods($e)) 

o questo per stampare abbastanza l'oggetto

\Doctrine\Common\Util\Debug::dump($e);