PHP - set_exception_handler 输出中的异常

Exceptions in PHP - set_exception_handler output

我现在开始使用 set_exception_handler。 我测试的第一个地方是我的 PDO 层的 try/catch 块。

我用不正确的数据库凭据强制了一个异常。 (这是在我应用

之前
<?php  

function log_exception($exception){
    print_r($exception);    
}

set_exception_handler("log_exception");

try { 
    $dbh = new PDO();
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    echo "connected!! \n";
} catch (PDOException $e) { 
    print_r($e); // let's see what it looks like
    throw new Exception($e); 
}
?>

您会在 catch 以及 log_exception 函数中看到 print_r

这是从 print_r($e):

中显示的内容
PDOException Object
(
    [message:protected] => SQLSTATE[28000] [1045] Access denied for user 'localhost'@'127.0.0.1' (using password: YES)
    [string:Exception:private] =>
    [code:protected] => 1045
    [file:protected] => /var/www/html/test.php
    [line:protected] => 35
    [trace:Exception:private] => Array
        (
            [0] => Array
                (
                    [file] => /var/www/html/test.php
                    [line] => 35
                    [function] => __construct
                    [class] => PDO
                    [type] => ->
                    [args] => Array
                        (
                            [0] => mysql:host=127.0.0.1;dbname=db_tests;charset=utf8
                            [1] => test
                            [2] => test
                        )

                )

        )

    [previous:Exception:private] =>
    [errorInfo] =>
)

这就是 print_r($exception)log_error() 中显示的内容功能:

Exception Object
(
    [message:protected] => exception 'PDOException' with message 'SQLSTATE[28000] [1045] Access denied for user 'localhost'@'127.0.0.1' (using password: YES)' in /var/www/html/test.php:34
Stack trace:
#0 /var/www/html/test.php(34): PDO->__construct('mysql:host=127.0...', 'test', 'test')
#1 {main}
    [string:Exception:private] =>
    [code:protected] => 0
    [file:protected] => /var/www/html/test.php
    [line:protected] => 34
    [trace:Exception:private] => Array
        (
        )

    [previous:Exception:private] =>
)

它们有什么不同? 我假设传递给 log_error() 函数的任何异常对象都将与 catch[=42 中生成的对象相同=].

我是不是漏掉了什么?

...

如果你想转发它,你应该抛出相同的异常,而不是新的异常:

throw $e;

这是因为它们是两个不同的异常。

正如您在此处看到的那样,PDOException 具有一些 Exception 没有的属性。 而你在 catch 中所做的是抛出一个新的 Exception,并将先前的异常作为消息。 Exception 构造函数期望将字符串作为消息传递,然后将获得 PDOExceptions 方法 __toString 的输出。 其他属性将根据最后一个 Exception 抛出的位置进行设置。

正如 Cristik 所说,如果你想传递 Exception,你可以使用 throw $e。这会将此 Exception 传递给异常处理程序。

当您创建一个新的 Exception 时,行和文件属性将根据此 Exception 的实例化位置进行设置。轨迹也会不同。但是只要把抓到的扔掉,这些都会完好无损。