首页 > 解决方案 > Laravel/Lumen 响应内容必须是实现 __toString() 的字符串或对象,“boolean”给定

问题描述

尝试使用 Lumen 返回 json 响应时出现以下错误。

The Response content must be a string or object implementing __toString(), "boolean" given.

在这里环顾四周后,似乎人们在不返回字符串时出现此错误,因此 Illuminate\Http\Response 中的 json_encode 失败。但是我肯定会返回一个字符串。

我正在为数据库连接获取用户输入,然后测试连接,如果有错误返回。

try{
  $connection = new \PDO($this->dsn, $this->username, $this->password);
  return true;
}catch(\Exception $e){
  return response()->json(['error' => $e->getMessage()]);
}

此时我收到上述错误。我在 $e->getMessage() 上做了一个 dd() 我得到了一个我期望的字符串。

string(53) "SQLSTATE[HY000] [1049] Unknown database 'test-db'"

当我返回一个带有字符串的数组时,为什么我仍然会收到错误消息?

标签: phplaravellumen

解决方案


推荐阅读