与PHP PDO进行比较时,Doctrine DBAL中的错误处理

时间:2015-04-08 18:47:48

标签: php pdo exception-handling doctrine-orm dbal

使用PDO,我们有\PDO::ATTR_ERRMODE,并将其设置为\PDO::ERRMODE_EXCEPTION,我们可以获得详细的异常堆栈跟踪(getTrace)。

如何使用DBAL?如何在DBAL级别设置它如何抛出错误?

DBAL是PDO实例的包装器,DBAL的大部分PDO方法都是相同的,还有ATTR_ERRMODE或其他类似的报告控制方法吗?

我希望使用set_error_handler来更好地控制错误的行为方式,并使用ERRMODE_EXCEPTION级别非常有用。

在PDO中:

<?php
$dsn = 'mysql:host='.$_SESSION['options']['host'].';port='.$_SESSION['options']['port'].';dbname='.$_SESSION['options']['dbname'].';charset='.$_SESSION['options']['charset'];
try {
    $conn = new \PDO($dsn, $_SESSION['options']['user'], $_SESSION['options']['pass']);
    $conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); // how to set this line in DBAL?
} catch (\PDOException $e) {
    trigger_error($e->getMessage(), E_USER_ERROR);
}
?>

DBAL中的相同内容:

<?php
require_once "lib/autoload.php";
$config = new \Doctrine\DBAL\Configuration();
$params = array(
    'dbname' => $_SESSION['options']['dbname'],
    'user' => $_SESSION['options']['user'],
    'password' => $_SESSION['options']['pass'],
    'host' => $_SESSION['options']['host'],
    'port' => $_SESSION['options']['port'],
    'driver' => 'pdo_mysql',
    'charset' => $_SESSION['options']['charset'],
);
try {
    $conn = \Doctrine\DBAL\DriverManager::getConnection($params, $config);
} catch (\Exception $e) {
    trigger_error($e->getMessage(), E_USER_ERROR);
}
?>

Doctrine DBAL版本:2.5.1

1 个答案:

答案 0 :(得分:3)

DBAL如何抛出错误

我检查过,看起来,对于PDO相关驱动程序的DBAL,默认情况下将PDO::ATTR_ERRMODE设置为PDO::ERRMODE_EXCEPTIONherehere),因此我们有详细的堆栈跟踪就像在PDO中一样。

实际上DBAL异常甚至比PDO更详细 - DBAL在错误描述中添加了一些信息(例如here)。

更改错误级别的选项

看来,DBAL缺乏改变错误出现程度的功能 无法将PDO::ATTR_ERRMODE更改为PDO::ERRMODE_SILENTPDO::ERRMODE_WARNING 从理论上讲,它应该由driverOptions option提供,如下所示:

$params = array(
    'dbname' => $options['dbname'],
    'user' => $options['user'],
    'password' => $options['pass'],
    'host' => $options['host'],
    'port' => $options['port'],
    'driver' => 'pdo_mysql',
    'charset' => $options['charset'],
    'driverOptions' => array(
        3 => 0 //here "3" is value of constant ATTR_ERRMODE, and "0" value of constant ERRMODE_SILENT
    )
);

它会起作用,但在连接声明后不久,DBAL会覆盖PDO::ATTR_ERRMODEhere)。
在PDO中还有setAttribute方法,我们可以设置PDO::ATTR_ERRMODE,但遗憾的是DBAL没有实现setAttribute方法。

如何控制DBAL中的错误

在DBAL中,我们已经拥有最佳级别的错误,我们可以捕获所有内容并更好地控制我们可以使用set_error_handler

<?php
/**
 * Error handler
 *
 * @param int $err_code the numeric error code
 * @param str $err_str description of the error
 * @param str $err_file the name of the file that contains the error
 * @param int $err_line the line number of the error
 * @param str $err_context details of the error
 */

function errorHandler($err_code, $err_str, $err_file, $err_line, $err_context) {
global $_SESSION;
    $_SESSION['errorCounter']++;
    $error_types = array (
        E_WARNING           => 'WARNING',
        E_NOTICE            => 'NOTICE',
        E_USER_ERROR        => 'USER ERROR',
        E_USER_WARNING      => 'USER WARNING',
        E_USER_NOTICE       => 'USER NOTICE',
        E_STRICT            => 'STRICT',
        E_DEPRECATED        => 'DEPRECATED',
        E_USER_DEPRECATED   => 'USER DEPRECATED'
    );
    $error_type = isset($error_types[$err_code]) ? $error_types[$err_code] : 'UNKNOWN ERROR TYPE['.$err_code.']';
    $err = "\n>--------------------------------------------------------------------";
    $err .= "\n".'EXCEPTION #'.$_SESSION['errorCounter'].':';
    $err .= "\n\n---- PHP ".$error_type.": ----";
    $err .= "\n".$err_str;

    //$err .= print_r($err_context, 1);
    if (isset($err_context['e'])){
        $err .= "\n\n---- STACKTRACE: ----";
        $dir_root = $_SERVER["DOCUMENT_ROOT"];
        $err .=  "\nroot: " . $dir_root;
        foreach ($err_context['e']->getTrace() as $a => $b) {
            $err .= "\n" . strval($a) . '# ';
            foreach ($b as $c => $d) {
                switch($c){
                    case 'file':
                        $err .=  str_replace($dir_root,'(root)',str_replace('\\','/',$d));
                        break;
                    case 'line':
                        $err .=  '(' . $d . "); ";
                        break;
                    case 'function':
                        $err .=  $c . ' ' . $d . "; ";
                        break;
                    case 'class':
                        $err .=  $c . ' ' . $d . "; ";
                        break;
                    case 'type':
                        $err .=  $c . ': ' . $d . "; ";
                        break;
                    case 'args':
                        foreach ($d as $e => $f){
                            $e = is_object($e) ? 'object' : is_array($e) ? 'array' : trim(preg_replace('/\s+/', ' ', $e));//do not return objects, arrays and change new lines to space
                            $f = is_object($f) ? 'object' : is_array($f) ? 'array' : trim(preg_replace('/\s+/', ' ', $f));//do not return objects, arrays and change new lines to space
                            $err .= 'args-' . $e . ': ' . $f . '; ';
                        }
                        break;
                }
            }
        }
    }
    else {
        $err .= "\n\n---- LOCATION: ----";
        $err .= "\n".$err_file.'(' . $err_line . ')';
    }

    $err .= "\n\n---- CONNECTION: ----";
    $err .= "\n".'host: '.$_SERVER['SERVER_NAME'];
    $err .= "\n".'client: '.$_SERVER['REMOTE_ADDR'];
    $err .= "\n".'timestamp: '.date("d-m-Y h:i:s A");
    $err .= "\n<--------------------------------------------------------------------\n";



    if (ini_get('log_errors')) {
        error_log($err, 0);
        if($err_code == E_USER_ERROR) {
            if (!$_SESSION['options']['debug']) {
                //send email with error
            }
        }
    }

    if ($_SESSION['options']['debug'])
        print("\n<pre>".$err."</pre>\n");

    return true;
}

set_error_handler("errorHandler");