2015-01-21 61 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(); 
} 

你应该总是添加错误检查和报告应用程序,请检查您尝试将其删除文件是否存在。