Exception的getTraceAsString
、getTrace
、getPrevious
方法
有时候程序出现的异常是前面的步骤引起的,例如thinkphp框架查询数据库时某个字段不存在,通过下面的方法只能够定位到抛出错误的文件、行以及错误信息,但是通过这些信息很难排查到在哪里设置了这个不存在的字段
$e->getMessage();
$e->getLine();
$e->getFile();
在文件D:\phpstudy_pro\WWW\new_boass\thinkphp\library\think\db\Connection.php 687行 发生错误:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'idd' in 'where clause'
这时候可以通过getTraceAsString
、getTrace
、getPrevious
方法来捕获调用栈信息来判断异常的原因
try {
$res = DiyPackPartSku::where('idd', 3453)->find()->delete();
}catch (\Exception $e){
echo $e->getTraceAsString();
// var_dump($e->getTrace());
// echo $e->getPrevious();
}
可以打印出调用栈来判断
#0 D:\phpstudy_pro\WWW\new_boass\thinkphp\library\think\db\Connection.php(844): think\db\Connection->query('SELECT * FROM `...', Array, false, false)
#1 D:\phpstudy_pro\WWW\new_boass\thinkphp\library\think\db\Query.php(3152): think\db\Connection->find(Object(think\db\Query))
#2 D:\phpstudy_pro\WWW\new_boass\application\service\repairdata\Demo.php(331): think\db\Query->find()
#3 D:\phpstudy_pro\WWW\new_boass\application\service\repairdata\RepairDataFactory.php(30): app\service\repairdata\Demo->testDelete(NULL, NULL, NULL, NULL, NULL, NULL)
#4 D:\phpstudy_pro\WWW\new_boass\application\command\RepairData.php(52): app\service\repairdata\RepairDataFactory->__call('testDelete', Array)
#5 D:\phpstudy_pro\WWW\new_boass\thinkphp\library\think\console\Command.php(175): app\command\RepairData->execute(Object(think\console\Input), Object(think\console\Output))
#6 D:\phpstudy_pro\WWW\new_boass\thinkphp\library\think\Console.php(675): think\console\Command->run(Object(think\console\Input), Object(think\console\Output))
#7 D:\phpstudy_pro\WWW\new_boass\thinkphp\library\think\Console.php(261): think\Console->doRunCommand(Object(app\command\RepairData), Object(think\console\Input), Object(think\console\O
utput))
#8 D:\phpstudy_pro\WWW\new_boass\thinkphp\library\think\Console.php(198): think\Console->doRun(Object(think\console\Input), Object(think\console\Output))
#9 D:\phpstudy_pro\WWW\new_boass\thinkphp\library\think\Console.php(115): think\Console->run()
#10 D:\phpstudy_pro\WWW\new_boass\think(22): think\Console::init()
#11 {main}