如何在try / catch语句laravel中记录错误?

时间:2016-07-24 01:52:50

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

我执行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;,但我仍然遇到此错误。

1 个答案:

答案 0 :(得分:0)

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

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