【问题标题】:Laravel: Is it possible to log stack trace when exception caught, and continue the execution?Laravel:是否可以在捕获异常时记录堆栈跟踪并继续执行?
【发布时间】:2018-08-15 00:13:30
【问题描述】:

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

【问题讨论】:

  • 这里是记录 debug_backtrace \Log::error(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 15));的更好方法
  • 不需要'json_encode'

标签: php laravel exception error-handling


【解决方案1】:

您可以简单地手动调用应用的异常处理程序:

<?php
try {
    foo();
} catch(\Throwable $e) {
    report($e);
}
bar();

在 Laravel 5.5 中引入,the report() helper 为您提供您通常会收到的相同错误报告,包括您可能为其他日志记录通道所做的任何自定义等。

【讨论】:

    【解决方案2】:

    Laravel 有一个辅助方法,请参阅 rescue 方法。

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

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

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

    【讨论】:

    • 这很有帮助。 rescue 方法最近添加到 Laravel 5.5 中,希望他们能在错误处理文档中添加一节来介绍它。无论如何,谢谢!
    • 是的,这是一个非常有说服力的 [双关语!] 答案,所以我删除了我的 ;-)
    • 这非常丑陋且不直观。
    猜你喜欢
    • 1970-01-01
    • 2011-11-13
    • 2013-02-21
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多