【问题标题】:How to log errors in try/catch statement laravel?如何在 try/catch 语句 laravel 中记录错误?
【发布时间】:2016-11-27 15:09:16
【问题描述】:

我正在执行一个 try catch 语句,我需要代码来执行某些操作,如果它未能捕获错误,请将其记录到 laravel 日志文件并继续循环。我的代码是:

    foreach ($logins as $login) {
        try {
            // Do something here
        } catch (Exception $e) {
            // Log errors
            \Log::error( $e->getMessage() );
            continue;
        }
    }  

但我收到一个错误,显示为

[Symfony\Component\Debug\Exception\FatalErrorException]                           
Namespace declaration statement has to be the very first statement in the script 

我在名称空间中使用了 \Log:: 并尝试添加 use Log;,但我仍然收到此错误。

【问题讨论】:

    标签: php logging error-handling try-catch laravel-5.2


    【解决方案1】:

    在其中一个脚本中,有一个与此类似的命名空间声明:

    namespace projects\name;
    

    错误被触发是因为在声明之前还有一些其他的脚本行。这是非法的:命名空间声明必须是第一个执行语句。

    一旦你解决了这个问题,那么这一行:

    \Log::error(...)
    

    也会导致你出错。前导 \ 表示您正在访问全局 PHP 命名空间中的类。如果您的Log 类位于特定命名空间中,例如projects\name,那么您可以通过以下两种方式之一使用该类。使用完全限定名称:

    \projects\name\Log::error(...)
    

    或者使用use 声明。

    use projects\name\Log; //early in the file. No need for leading \
    ...
    Log::error(...)
    

    【讨论】:

    • 谢谢,这是我的问题。还必须为 \Exception $e 添加一个 \,因为 laravel 是命名空间的。
    • Log 是 Laravel 根(全局)命名空间中的外观。
    猜你喜欢
    • 2014-09-09
    • 1970-01-01
    • 2021-06-04
    • 2013-05-20
    • 2012-03-13
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    相关资源
    最近更新 更多