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

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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?