Laravel: Is it possible to log stack trace when exception caught, and continue the execution?

ぃ、小莉子 提交于 2021-02-18 22:42:34

问题


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}
"}

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();

回答1:


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();



回答2:


You can simply call your app's exception handler manually:

<?php
use App\Exceptions\Handler;

try {
    foo();
} catch(\Exception $e) {
    $h = new Handler(app());
    $h->report($e);
}
bar();

This gives you the same error reporting you'd normally get, including any customizations you may have made for additional logging channels, etc.



来源:https://stackoverflow.com/questions/49142667/laravel-is-it-possible-to-log-stack-trace-when-exception-caught-and-continue-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!