Laravel:是否可以在捕获到异常时记录堆栈跟踪并继续执行? [英] Laravel: Is it possible to log stack trace when exception caught, and continue the execution?

查看:51
本文介绍了Laravel:是否可以在捕获到异常时记录堆栈跟踪并继续执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Laravel has readable log and stacktrace when exception caught, for example:

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())); 记录错误,这确实很丑陋且很难追踪.示例代码:

The question is: is it possible to catch the exception myself, and log the same format of the stacktrace, and continue the program execution. By far, I am logging the error by Log::error(json_encode(debug_backtrace())); which is really ugly and hard to trace. The example code:

try {
    foo();
} catch(\Exception $e) {
    Log::error(json_encode(debug_backtrace()));
}
bar();

推荐答案

Laravel为此提供了一个辅助方法,请参见

Laravel has a helper method just for this, see the rescue method.

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

使用您的示例,它看起来像:

Using your example it would look like:

rescue(function () { 
    return foo(); 
});

bar();

这篇关于Laravel:是否可以在捕获到异常时记录堆栈跟踪并继续执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆