简体   繁体   English

如何在实体中捕获异常?

[英]How to catch exceptions in entity?

I have a method in my entity with @ORM\\PostRemove() which removes an associated file. 我的实体中有一个使用@ORM \\ PostRemove()的方法,该方法可以删除关联的文件。

I wonder if I should do something like this: 我想知道是否应该做这样的事情:

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

Does it make sense to catch an exception and do nothing in catch block? 捕获异常而在catch块中什么也不做是否有意义? Or maybe I shouldn't catch exception here, but then, where should I do it? 或者也许我不应该在这里捕获异常,但是那我应该在哪里做呢? Should it be an exception from LifecycleCallback method? 这是LifecycleCallback方法的例外吗? I've read here that I shouldn't use logger in entity, so I'm confused what to put there instead. 我在这里读到,我不应该在实体中使用记录器,所以我很困惑放置在那里的内容。

Your entity shouldn't really contain business logic for your application, its purpose is to map objects to the database records. 您的实体不应真正包含应用程序的业务逻辑,它的目的是将对象映射到数据库记录。

The way to approach this depends on the application, for example if you have a File Controller and a removeAction within then the best place to remove the file would likely be here. 解决此问题的方法取决于应用程序,例如,如果您在其中具有文件控制器和removeAction,则最好在此处删除文件。

As an example: (psuedo code) 例如:(伪代码)

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();
}

You should always add error checking and reporting in your application, check that a file exists before you attempt to remove it. 您应该始终在应用程序中添加错误检查和报告功能,并在尝试删除文件之前检查文件是否存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM