2015-01-21 95 views
0

我在@ORM \ PostRemove()的實體中有一個方法,它刪除了一個關聯的文件。如何在實體中捕獲異常?

我不知道我是否應該做這樣的事情:

try { 
    unlink($file); 
} catch (\Exception $e) { 
    // Nothing here?   
} 

是否有意義捕捉異常,什麼也不做的catch塊?或者,也許我不應該在這裏發現異常,但是,我應該在哪裏做?它應該是LifecycleCallback方法的異常嗎? 我讀過here,我不應該在實體中使用記錄器,所以我很困惑應該在那裏放置什麼。

回答

1

您的實體不應該真正包含您的應用程序的業務邏輯,其目的是將對象映射到數據庫記錄。

解決此問題的方法取決於應用程序,例如,如果您有文件控制器和removeAction,那麼刪除文件的最佳位置可能就在此處。

爲例:(僞代碼)

public function removeAction($id) { 
    $em = $this->getDoctrine()->getEntityManager(); 
    $file = $em->getRepository('FileBundle:File')->find($id); 

    if (!$file) { 
     throw $this->createNotFoundException('No file found for id '.$id); 
    } 

    $filePath = $file->getPath(); 
    if (file_exists($filePath) { 
     try { 
      unlink($filePath); 
     } 
     catch(Exception $e) { 
      // log it/email developers etc 
     } 
    } 

    $em->remove($file); 
    $em->flush(); 
} 

你應該總是添加錯誤檢查和報告應用程序,請檢查您嘗試將其刪除文件是否存在。