How can I deliver an error page in Slim framework when an Exception is thrown outside of a route?

Viewed 9109

I'm trying to wrap my head around the order of operations for dealing with Exceptions thrown in a Slim framework app and the final page delivery. Basically, if I throw an Exception in a class I'd like Slim to deliver my pretty Twig 500 page, but I can't even get Slim to deliver its own normal error page when an exception is thrown outside of a route.

Given this database class constructor:

public function __construct(array $connection, \Slim\Slim $slim) {
  $this->slim = $slim;
  try {
    $this->db = new \PDO(...);
    $this->db->setAttribute(\PDO::ATTR_EMULATE_PREPARES, FALSE);
    $this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
 } catch (\PDOException $e) {
    // How can I kill further execution here and have Slim deliver a 500?
 }
}

If I run $this->slim->error(); I get Fatal error: Uncaught exception 'Slim\Exception\Stop'.

Ideally, I'd like to do something like:

  1. Log it via $this-slim->log->error("Unable to connect to database.");
  2. Stop attempting to execute further actions in my DB class (which would all fail and throw fatal exception)
  3. Deliver the page via a 500.twig template file.

Any help or direction would be much appreciated.

1 Answers
Related