【问题标题】:Slim Framework DB Service Exception HandlingSlim Framework DB 服务异常处理
【发布时间】:2016-10-03 20:41:00
【问题描述】:

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

数据库连接

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

如果数据库连接引发 PDO(或通用)异常怎么办?在 v2 中,我有类似的东西

$app->error

现在呢?我也定义了一个自定义的errorHandler,我怎样才能以某种方式“重定向”对该路由的控制?

【问题讨论】:

  • “我怎样才能以某种方式“重定向”对该路由的控制?”是什么意思?

标签: php pdo dependency-injection slim slim-3


【解决方案1】:

Slim 3 的错误处理非常简单,如explained in the documentation

由于您在实例化 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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 2011-07-26
    • 2015-06-06
    • 2020-10-20
    相关资源
    最近更新 更多