精简框架DB服务异常处理


Slim Framework DB Service Exception Handling

我正在升级到slim v3。我应该如何使用数据库连接?我正在考虑一个注入了痘痘的服务:

DBConnection

final class DBConnection {
    private $db;
    public function __construct() {
        try {
            // Code to open up a DB connection in $db var...
        } catch (Exception $ex) {
            // TODO $app->error ?
        }
    }
    public function getDB() {
        return $this->db;
    }
}

index . php

$container = new 'Slim'Container;
$container['db'] = function($container) {
    $connection = new DBConnection();
    return $connection->getDB();
};

如果db连接引发PDO(或泛型)异常怎么办?在v2中,我写了

$app->error

现在什么?我也定义了一个自定义errorHandler,我如何以某种方式"重定向"该路由的控制?

Slim 3的错误处理非常简单,如文档中所述。

由于您在实例化Slim'App之前定义了容器服务,因此以以下方式定义错误处理程序(在index.php中):

$container['errorHandler'] = function($container) {
    return function ($request, $response, $exception) use ($container) {
        return $container['response']->withStatus(500)
                                     ->withHeader('Content-Type', 'text/html')
                                     ->write($exception->getMessage());
    };
};

所有异常都将被定义的处理程序捕获,只要:

  • 先前未捕获异常(如在示例代码中)
  • 异常不属于以下情况:
    • Slim'Exception'MethodNotAllowedException
    • Slim'Exception'NotFoundException
    • Slim'Exception'SlimException

对于前两个,您也可以定义自己的处理程序。

那么,回到你的例子:

final class DBConnection {
    private $db;
    public function __construct() {
        // Code to open up a DB connection in $db var...
        // Don't have to catch here
    }
    public function getDB() {
        return $this->db;
    }
}