在PHP MVC应用程序中捕获异常的位置?

时间:2015-07-07 13:26:34

标签: php exception logging exception-handling

我有用于练习OOP和MVC技能的中小型PHP应用程序。我有 init / bootstrap 文件,该文件呼叫路由器,他们呼叫控制器 - > 服务层 - > 存储库(数据库)然后将变量发送回查看图层(使用DiC / IOC处理的所有依赖项)。

我创建了抽象类BaseException ,它扩展了Core Exception 类。然后我有不同的异常类 - DatabaseException,FileException等。

示例触发异常: 在数据库层中我尝试从数据库中获取数据,如果失败则会抛出新的DatabaseException。

示例2: 在我处理文件包含,保存,删除的类中 - 如果发生错误,则会抛出新的FileException。

在init / bootstrap文件中或者在BaseController中放置try catch代码的位置?但是如果Controller失败并且它抛出某种ControllerException会怎样。

在我看来,它可能看起来像这样( init.php 文件):

try {
    // create new router
    $router = $container->get('Router');
    $router->import'Config/routes.php');

    // run the router
    $router->route();

    // load controller
    $dispatcher = $container->get('Dispatcher');
    $dispatcher->load();
} catch (DatabaseException $e) {
    echo "Database error!";
    $log->log('Database error', $e->getMessage());
} catch (FileException $e) {
    echo "File error!";
    $log->log('File error', $e->getMessage());
} catch (Exception $e) { // default
    echo "Some exceptional error!";
    $log->log('Default exception', $e->getMessage());
}

还有一个问题,如何记录这些异常(错误),如上例所示,还是应该在BaseException中注入Log类并处理日志记录?

1 个答案:

答案 0 :(得分:1)

与普通的php一样,你可以在任何地方实现try / catches。

在我的项目中(作为MVC框架用户),我通常在我的控制器方法中处理异常,因为他们有责任处理应用程序中的进程。但如果需要,我会在中间件甚至模型中实现它,如果我愿意的话。

在你的情况下,似乎你想让你的框架在将它输出到用户界面之前处理异常,就像Laravel(还有很多其他人)那样。

您可以使用PHP中的set_exception_handler()函数完成此操作。

以下是基于docs示例的示例:

set_exception_handler(function($exception){

    //you could write in a log file here for example...
    echo "Uncaught exception: " , $exception->getMessage(), "\n";

});