2016-03-01 73 views
4

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

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

+0

这是启动应用程序并捕获异常的正确方法。 **你想要捕捉什么类型的错误?**例如,如果你将db密码更改为不正确的密码,你的代码将会工作。但是,如果你犯了一个解析错误,它将不会被捕获。 –

回答

2

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

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

你说:“当出现错误”,如果你要处理错误,然后在上面添加错误处理程序Phalcon bootstrap(public/index.php)文件。

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

如果你想显示你需要改变这一行你php.ini文件中的PHP解析错误:

display_errors = on 

您可能需要重新启动你的web服务器,此更改生效。


如果您不能确定在ini文件所在,输出下面的一行代码:

<?php phpinfo(INFO_GENERAL) ?> 

这应该显示php.ini文件


的位置另一个注意事项。捕捉这样的错误并不是一个好习惯。 Phalcon提供了不同的方式来捕捉错误。

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

有关完整示例,请参阅the Phalcon INVO repository

0

在app /配置/ 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 

);