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

懵懂的女人 提交于 2019-12-05 12:12:55

You're running into grief because Slim's error handling hasn't been configured because your app never makes it all the way to \Slim\Slim::run().

Two things to do:

1) I recommend adding your database class (and other similar classes) into Slim's Dependency Injection container.

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

That will allow lazy loading of your database connection. The class won't be created until you use it. At that point, and I'm assuming here, you will be in a route, \Slim\Slim::run() will have been called, and the Slim error handling will be in place.

2) Now that the exception isn't going to occur before your app is fully configured, you can use logging:

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;
}

along with Slim's custom error handling.

$app->error(function(\Exception $e) use ($app) {
    if ($e instanceof \PDOException) {
        return $app->render('500.twig', array(), 500);
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!