/**
* 获取所有先前链接错误的顺序数组
*
* @param Throwable $error
*
* @return Throwable[]
*/
function getChain(Throwable $error) : array
{
$chain = [];
do {
$chain[] = $error;
} while ($error = $error->getPrevious());
return $chain;
}
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Exception::getPrevious — 返回前一个 Throwable
返回前一个 Throwable(已作为 Exception::__construct() 的第三个参数传递)。
此函数没有参数。
示例 #1 Exception::getPrevious() 示例
循环遍历并打印出异常跟踪。
<?php
class MyCustomException extends Exception {}
function doStuff() {
try {
throw new InvalidArgumentException("You are doing it wrong!", 112);
} catch(Exception $e) {
throw new MyCustomException("Something happened", 911, $e);
}
}
try {
doStuff();
} catch(Exception $e) {
do {
printf("%s:%d %s (%d) [%s]\n", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
} while($e = $e->getPrevious());
}
?>
以上示例将输出类似以下内容
/home/bjori/ex.php:8 Something happened (911) [MyCustomException] /home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException]
/**
* 获取所有先前链接错误的顺序数组
*
* @param Throwable $error
*
* @return Throwable[]
*/
function getChain(Throwable $error) : array
{
$chain = [];
do {
$chain[] = $error;
} while ($error = $error->getPrevious());
return $chain;
}