How can I provide a page with an error in the Slim structure when an exception is thrown out of the route?

I'm trying to get my head around the order of operations related to Exceptions thrown into the Slim platform app and the final delivery of the page. Basically, if I throw an exception in the class, I would like Slim to deliver my beautiful Twig 500 page, but I can't even get Slim to deliver its own regular error page when the exception is thrown out of the route.

Given this constructor of the database class:

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 would like to do something like:

  • Log in through $this-slim->log->error("Unable to connect to database.");
  • Stop trying to perform further actions in my DB class (so that everything fails and throws a fatal exception)
  • 500.twig.

.

+4
1

, Slim , \Slim\Slim::run().

:

1) ( ) Slim Injection.

$app->container->singleton('db', function () use ($app) {
    return new Database($app);
});

. , . , , , \Slim\Slim::run() , Slim .

2) , , , :

public function __construct(\Slim\Slim $app) {
    $this->slim = $app;

    try {
        $this->db = new \PDO('sqlite:/does/not/exist');
    } catch (\PDOException $p) {
        $this->slim->log->error('BAD THINGS');
        return $this->slim->error();
    }

    return $this;
}

.

$app->error(function(\Exception $e) use ($app) {
    if ($e instanceof \PDOException) {
        return $app->render('500.twig', array(), 500);
    }
});
+9

All Articles