在 phalcon 中处理全局异常


Handle global exceptions in phalcon

我想知道,在Phalcon中处理异常的最佳方法是什么?我想为发生错误时创建一个默认错误页面。所以我重写了/app/public/index.html

<?php
error_reporting(E_ALL);
try {
    /**
     * Define some useful constants
     */
    define('BASE_DIR', dirname(__DIR__));
    define('APP_DIR', BASE_DIR . '/app');
    require_once __DIR__ . '/../vendor/autoload.php';

    /**
     * Read the configuration
     */
    $config = include APP_DIR . '/config/config.php';
    /**
     * Read auto-loader
     */
    include APP_DIR . '/config/loader.php';
    /**
     * Read services
     */
    include APP_DIR . '/config/services.php';
    /**
     * Handle the request
     */
    $application = new 'Phalcon'Mvc'Application($di);
    echo $application->handle()->getContent();
} catch (Exception $e) {
    echo 'This is where I want my handling to be';
}

但是,当抛出错误时,我会不断收到默认的Chrome 500错误窗口。错误已记录到 OS X 的错误控制台,但我没有看到我的回声。我做错了什么?

使用多个 catch 块,而不仅仅是 ''Exception 添加特定类型的异常,如 ''PDOException

try
{
 /* something */
}
catch('Exception $e )
{
   handler1( $e );
}
catch ( 'PDOException $b )
{
   handler2( $e );
}
// add more ex here

您说"发生错误时",如果要处理错误,请在 Phalcon 引导程序(公共/索引.php)文件的顶部添加错误处理程序。

function handleError($errno, $errstr) {
    echo "<b>Error:</b> [$errno] $errstr<br>";
    //do what ever
    die();
}
set_error_handler("handleError");

in app/config/service.php

use 'Phalcon'Mvc'Dispatcher as PhDispatcher;
.
.
.

$di->set(
'dispatcher',
function() use ($di) {
    $evManager = $di->getShared('eventsManager');
    $evManager->attach(
        "dispatch:beforeException",
        function($event, $dispatcher, $exception)
        {
            switch ($exception->getCode()) {
                case PhDispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                case PhDispatcher::EXCEPTION_ACTION_NOT_FOUND:
                    $dispatcher->forward(
                        array(
                            'namespace' => 'App'Controllers'Web',
                            'controller' => 'error',
                            'action'     => 'show404',
                        )
                    );
                    return false;
            }
        }
    );
    $dispatcher = new PhDispatcher();
    $dispatcher->setEventsManager($evManager);
    return $dispatcher;
},
true

);

如果你想

显示PHP解析错误,你需要在PHP.ini文件中更改这一行:

display_errors = on

您可能需要重新启动 Web 服务器才能使此更改生效。


如果不确定 ini 文件的位置,请输出以下代码行:

<?php phpinfo(INFO_GENERAL) ?>

这应该显示 PHP.ini 文件的位置


另一方面。像这样发现你的错误不是一个好的做法。Phalcon提供了不同的方法来捕获错误。

$eventsManager->attach('dispatch:beforeException', new NotFoundPlugin);

有关完整示例,请参阅 Phalcon INVO 存储库。