Laravel错误:方法IlluminateViewView::__toString()不能引发异常


Laravel Error: Method IlluminateViewView::__toString() must not throw an exception

你在Laravel工作时看到这个可爱的错误了吗?

Method Illuminate'View'View::__toString() must not throw an exception

我看过,非常讨厌。我发现了引发此错误的两个原因。我只是想帮助人们不要花太多时间。

查看答案&以下情况。:)

有一个非常简单的解决方案:不要将View对象强制转换为字符串。

不要:echo View::make('..');echo view('..');

Do:echo View::make('..')->render();echo view('..')->render();

对于PHP版本<7.4通过强制转换视图,它自动使用__toString()方法,不能抛出异常。如果手动调用render(),则会正常处理异常。如果视图中出现错误,情况就是这样——laravel抛出异常。

在PHP中修复了>=7.4您不应该遇到这个问题:https://wiki.php.net/rfc/tostring_exceptions.

对于PHP版本<7.4:这实际上是PHP的限制,而不是Laravels。在此处阅读有关此"功能"的更多信息:https://bugs.php.net/bug.php?id=53648

情况1:正在尝试打印出数组中的值。

答案1:尝试打印出阵列。你确定这是一个数组吗?当它是一个对象而不是数组时,我得到了这个错误。试着打印一下,看看你得到了什么。

情况2:你有这样一个相关的数组:

Array
    (
        [post_id] => 65
        [post_text] => Multiple Images!
        [created_at] => 2014-10-23 09:16:46
        [updated_on] => 
        [post_category] => stdClass Object
            (
                [category_label] => Help Wanted
                [category_code] => help_wanted
            )
        [employee_full_name] => Sam Jones
        [employee_pic] => /images/employee-image-placeholder.png
        [employee_email] => jon@gmail.com
        [post_images] => Array
            (
                [0] => stdClass Object
                    (
                        [image_path] => 9452photo_2.JPG
                    )
                [1] => stdClass Object
                    (
                        [image_path] => 8031photo_3.JPG
                    )
            )
    )

当您尝试直接在视图中访问post_images数组时,它会抛出一个错误否。课题什么你Do。

答案2:查看您调用View的所有位置。这里发生的事情是,我试图在一个没有提供post_images数组的区域的其他地方访问相同的视图。花了很长时间才弄明白。

我希望这能帮助其他人我只知道我一直犯的错误对我没有任何帮助。

当我的案例中的对象$expression = new Expression();与参数变量submitExpression($intent, $bot_id, **$expression**){相同时,我遇到了这样的错误。有关更多详细信息,请查看下面的代码。

private function submitExpression($b_id, $expression){
   $expression = new Expression();
   $expression->b_id = $b_id;
   $expression->expression = $expression;
   $expression->save();
}

所以我把上面的代码改成了类似的代码

private function submitExpression($b_id, $statement){      
   $expression = new Expression();
   $expression->b_id = $b_id;
   $expression->expression = $statement;
   $expression->save(); 
}

一切都很好,希望你觉得这有帮助。

我的问题是找出代码中调用View::__toString()的确切位置,这样我就可以使用render()来修复它(正如其他答案所示)。

要找到它,请临时编辑vendor/laravel/framework/src/Illuminate/View/View.php,添加当前堆栈跟踪的日志:

public function __toString()
{
    // Next line added temporarily to debug.
    logger("This causes the '__toString() must not throw an exception' problem: " 
        . (new 'Exception())->getTraceAsString());
    return $this->render();
}

类似的错误是:

FooController.php中的FatalErrorException第0行:Method App''Models''Foo::__toString()不能引发异常

这只是一个糟糕的任务:$foo.= new Foo;

而不是:$foo = new Foo;