【问题标题】:__toString() must not throw an exception error when using string__toString() 在使用字符串时一定不能抛出异常错误
【发布时间】:2014-02-01 23:18:30
【问题描述】:

我正在将 Laravel 4 用于我正在进行的项目。我需要从帖子中检索第一条评论。我使用以下代码来执行此操作。

$comments = Comment::where('post_id', $post->id)->first();

这成功检索了第一条评论(我知道这是因为我print_r-ed $comments 并且它返回了所有正确的信息)。

但是,下面这行代码触发了错误__toString() must not throw an exception

<td>{{$comments->content}}</td>

当我print_r-ed 它返回类型字符串时,也返回了正确的字符串。那它为什么还要在$comments-&gt;content 已经是字符串的情况下尝试将其转换为类型字符串?

【问题讨论】:

  • 它表示View 类的__toString() 方法不能抛出异常。可能,您的视图中有一些错误
  • 这是你的问题吗:stackoverflow.com/questions/2429642/…
  • Symfony \ Component \ Debug \ Exception \ FatalErrorException Method Illuminate\View\View::__toString() must not throw an exception 是完整的错误@neoascetic。另外,那会是什么错误?
  • @735Tesla 没有告诉我我做错了什么
  • @InsertNameHere 未定义变量。未闭合的花括号。事实上,任何类型的错误

标签: php laravel


【解决方案1】:

我知道这是一个老问题,但对于未来的谷歌人(比如我)来说,还有另一种方法可以解决这个错误,它独立于你的框架:

public function __toString() 
{
    try {
       return (string) $this->attributeToReturn; // If it is possible, return a string value from object.
    } catch (Exception $e) {
       return get_class($this).'@'.spl_object_hash($this); // If it is not possible, return a preset string to identify instance of object, e.g.
    }
}

您可以将它与没有框架的自定义类一起使用,或者与 Symfony2/Doctrine 中的实体一起使用......它也可以。

【讨论】:

    【解决方案2】:

    根据您提供的信息和我对 Laravel 的经验,我敢打赌导致异常的代码行不是您在问题中提出的行。

    <td>{{$comments->content}}</td>
    

    这个异常是在抱怨视图抛出异常。如果此特定行是问题所在,您将获得关于 $cmets->content 如何无法转换为字符串的更具描述性的异常。你也已经测试过它确实是一个字符串。

    我建议找到您的“视图”对象与视图相呼应的位置,然后像这样进行更改。

    {{ View::make('yourbladefile')->__tostring() }}
    

    通过提供更准确和信息丰富的例外,这对我有用。有关您的异常的更多信息,您应该查看Why it's impossible to throw exception from __toString()?

    这就是最初给我这个想法的原因。我知道这不是一个完美的答案,所以请让我知道这是否有效,如果事实并非如此,我会更新我的答案。祝你好运。

    【讨论】:

    • 这是一个很棒的提示!我能够通过使用 var_dump($somevar) 剥离异常链,直到找到问题的根源(这是一个未初始化的关系)。
    猜你喜欢
    • 2021-08-03
    • 1970-01-01
    • 2017-09-09
    • 2014-12-19
    • 2019-05-12
    • 2016-07-13
    • 2011-01-26
    • 2015-04-04
    • 2021-07-09
    相关资源
    最近更新 更多