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

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

报告相同问题?