gpt4 book ai didi

php - Laravel:是否可以在捕获异常时记录堆栈跟踪并继续执行?

转载 作者:行者123 更新时间:2023-12-05 00:20:30 24 4
gpt4 key购买 nike

Laravel 在异常捕获时具有可读的日志和堆栈跟踪,例如:

production.ERROR: Command "test" is not defined.

Did you mean this?
make:test {"exception":"[object] (Symfony\\Component\\Console\\Exception\\CommandNotFoundException(code: 0): Command \"test\" is not defined.

Did you mean this?
make:test at {root}/vendor/symfony/console/Application.php:618)
[stacktrace]
#0 {root}/vendor/symfony/console/Application.php(229): Symfony\\Component\\Console\\Application->find('test')
#1 {root}/vendor/symfony/console/Application.php(148): Symfony\\Component\\Console\\Application->doRun(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#2 {root}/vendor/laravel/framework/src/Illuminate/Console/Application.php(88): Symfony\\Component\\Console\\Application->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#3 {root}/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(121): Illuminate\\Console\\Application->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#4 {root}/artisan(37): Illuminate\\Foundation\\Console\\Kernel->handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#5 {main}
"}

问题是:是否可以自己捕获异常,并记录相同格式的stacktrace,并继续程序执行。到目前为止,我正在通过 Log::error(json_encode(debug_backtrace())); 记录错误这真的很难看,很难追踪。示例代码:
try {
foo();
} catch(\Exception $e) {
Log::error(json_encode(debug_backtrace()));
}
bar();

最佳答案

Laravel 有一个专门用于此的辅助方法,请参阅 rescue方法。

return rescue(function () { 
return $this->method();
});

使用您的示例,它看起来像:
rescue(function () { 
return foo();
});

bar();

关于php - Laravel:是否可以在捕获异常时记录堆栈跟踪并继续执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49142667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com