/**
* 获取所有先前链接错误的顺序数组
*
* @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;
}
也许我已经晚了(5.2 不受支持)。但是如果你想在 PHP < 5.3 中使用“先前异常”的功能,或者编写兼容的代码,你可以使用以下方式:
<?php
抽象类 App_Exception_PreviousNativeAbstract 扩展 Exception {
public static $printPrevious = true;
public function __toString() {
$result = array();
$result[] = sprintf("异常 '%s',消息为 '(%s) %s',位于 %s:%d", get_class($this), $this->code, $this->message, $this->file, $this->line);
$result[] = '---[堆栈跟踪]:';
$result[] = $this->getTraceAsString();
if (self::$printPrevious) {
$previous = $this->getPrevious();
if ($previous) {
do {
$result[] = '---[前一个异常]:';
$result[] = sprintf("异常 '%s',消息为 '(%s) %s',位于 %s:%d", get_class($previous), $previous->getCode(), $previous->getMessage(), $previous->getFile(), $previous->getLine());
$result[] = '---[堆栈跟踪]:';
$result[] = $previous->getTraceAsString();
} while(method_exists($previous, 'getPrevious') && ($previous = $previous->getPrevious()));
}
}
return implode("\r\n", $result);
}
}
抽象类 App_Exception_PreviousLegacyAbstract 扩展 App_Exception_PreviousNativeAbstract {
protected $previous;
public function __construct($message, $code = 0, Exception $previous = null) {
$this->previous = $previous;
parent::__construct($message, $code);
}
public function getPrevious() {
return $this->previous;
}
}
if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
抽象类 App_Exception_PreviousAbstract 扩展 App_Exception_PreviousNativeAbstract {}
}
else {
抽象类 App_Exception_PreviousAbstract 扩展 App_Exception_PreviousLegacyAbstract {}
}
类 App_Exception 扩展 App_Exception_PreviousAbstract {
public function __construct($message, $code = 0, Exception $previous = null) {
parent::__construct($message, 0, $previous);
}
}
// 示例:
try {
// ...
抛出 new Exception('异常消息');
// ...
} catch (Exception $e) {
抛出 new App_Exception('应用程序异常消息', 0, $e);
}
?>