dqde43215 2018-05-13 19:22
浏览 48
已采纳

保存实体时捕获学说异常

While digging into the exception handling of Doctrine, I stumbled on this code example that made me wonder out loud if this was overkill or could be of some use:

  // Save entity
        try {
            $em->persist($someEntity);
            $em->flush();

            $this->logger->info("Saved someEntity");

        } catch (DBALException $e) {
            $this->logger->addError("DBALException [{code}]: {message}",
                array('code' => $e->getCode(), $e->getMessage()));
        } catch (PDOException $e) {
            $this->logger->addError("PDOException [{code}]: {message}",
                array('code' => $e->getCode(), $e->getMessage()));
        } catch (ORMException $e) {
            $this->logger->addError("ORMException [{code}]: {message}",
                array('code' => $e->getCode(), $e->getMessage()));
        } catch (Exception $e) {
            $this->logger->addError("Exception [{code}]: {message}",
                array('code' => $e->getCode(), $e->getMessage()));
        }

I always just used the generic exception (the last in code example), and was wondering if this is overkill in most cases unless one wants to handle one of the defined exception differently?

  • 写回答

1条回答 默认 最新

  • dqbh8054 2018-05-13 19:29
    关注

    I think that isn't an overkill because in some specific case you need to understand which error it's generate by the save of an entity.

    For example if you have a problem about parameters number because you create a custom query you may wonder to know if is a PDO problem or a DBAL problem to understand where to change your code.

    In many case you don't need all this exception but in other case is important to understand which part of your code fail exactly to fix the bug.

    What have you posted is a rare example on how to catch an exception, but for me when you are into a very deep and complex problem is very important to understand clearly and faster which exception is generated and from which vendor / dependency / library

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求恶意流量检测系统搭建教程( C++ python C)
  • ¥15 mmseqs内存报错
  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)
  • ¥20 web页面如何打开Outlook 365的全球离线通讯簿功能
  • ¥15 io.jsonwebtoken.security.Keys