处理phalcon中的全局异常

时间:2016-03-01 13:40:03

标签: php 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的错误控制台,但我没有看到我的回声。我做错了什么?

3 个答案:

答案 0 :(得分:3)

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

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

你说&#34;当发生错误&#34;时,如果你想处理错误,那么在Phalcon bootstrap(public / index.php)文件的顶部添加错误处理程序。

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

答案 1 :(得分:0)

If you want to show the PHP parse errors you need to alter this line in you PHP.ini file:

display_errors = on

You might need to restart your webserver for this change to take effect.


If you are unsure where the ini file is located, output the following line of code:

<?php phpinfo(INFO_GENERAL) ?>

This should display the location of the PHP.ini file


On an other note. Catching your errors like that is not a good practise. Phalcon provides different ways to catch errors.

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

Refer to the Phalcon INVO repository for the full example.

答案 2 :(得分:0)

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

);