Stephane Gosselin
Stephane Gosselin

Reputation: 9148

Catching doctrine exceptions when saving entity

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?

Upvotes: 3

Views: 1252

Answers (1)

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35963

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

Upvotes: 4

Related Questions