Skip to main content
3 of 3
removed "Drupal" from the title
avpaderno
  • 97.9k
  • 15
  • 164
  • 284

Handle database connection exception via custom handler

I want to catch the database connection exceptions with a custom handler. I have already built an handler which is overriding the default logger factory, but now I want to use that custom handler to log database exceptions, without hacking the core.

I can see the connection driver uses the following code in open().

try {
  $pdo = new \PDO($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);
}
catch (\PDOException $e) {
  if ($e->getCode() == static::DATABASE_NOT_FOUND) {
    throw new DatabaseNotFoundException($e->getMessage(), $e->getCode(), $e);
  }
  if ($e->getCode() == static::ACCESS_DENIED) {
    throw new DatabaseAccessDeniedException($e->getMessage(), $e->getCode(), $e);
  }
  throw $e;
}

I am not sure how I can catch the exception and log it using the handler. How can I achieve this?

arpitr
  • 7.9k
  • 2
  • 23
  • 48