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 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败