处理 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 错误 window。错误记录到 OS X 的错误控制台,但我没有看到我的回显。我做错了什么?

如果您想显示 PHP 解析错误,您需要更改 PHP.ini 文件中的这一行:

display_errors = on

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


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

<?php phpinfo(INFO_GENERAL) ?>

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


另一个注意事项。像那样捕捉你的错误不是一个好习惯。 Phalcon 提供了不同的方法来捕获错误。

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

完整示例请参阅 the Phalcon INVO repository

在 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

);

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

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

你说 "when an error occurs",如果你想处理错误然后在 Phalcon bootstrap (public/index.php) 文件的顶部添加错误处理程序。

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