2013-12-02 35 views
7

Làm thế nào để bắt ngoại lệ trong bộ điều khiển và hiển thị thông báo flash trong Symfony 2?Làm thế nào để bắt ngoại lệ trong 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(), 
)); 

Tôi nên làm gì trong khối catch?

+0

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

+0

toString ($ e) không hoạt động. Nó cho thấy FatalErrorException: Lỗi: Gọi hàm undefined toString() – Swass

+0

'echo (string) $ e;' hoặc tốt hơn, gửi cho bạn một email trên một site sản xuất: 'mail ('[email protected]', 'Ngoại lệ trong script ... ', var_export ($ e, true)); ' – DanFromGermany

Trả lời

13

Bạn nên chú ý đến các ngoại lệ có thể được nêu ra :

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' không được dùng như 'Symfony 2.4' và bị loại bỏ thành' Symfony 3.0'. Vui lòng xem xét một số chỉnh sửa – Trix

+0

Thx, tôi đã cập nhật bài đăng của mình. –

3

Đọc kỹ điều này, bắt ngoại lệ và tạo ra đầu ra trong cành được trình bày rõ ràng tại đây. :)

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

hơn nữa,

bạn có thể sử dụng phương pháp nguyên thủy này để có được phương pháp của một lớp:

print_r(get_class_methods($e)) 

hay này đến khá in đối tượng của bạn

\Doctrine\Common\Util\Debug::dump($e); 
Các vấn đề liên quan