/**
* 取得所有先前鏈式錯誤的序列陣列
*
* @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("您操作方式錯誤!", 112);
} catch(Exception $e) {
throw new MyCustomException("發生了一些事情", 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;
}