LoginSignup
16
10

More than 3 years have passed since last update.

オブジェクトをLog出力しようとしてエラーになった

Posted at

同じことをやらかしそうな未来の自分用のメモです。

Object of class stdClass could not be converted to string が吐き出される

APIからのレスポンスを確認しようとしていたときのできごと。

$response = $this->getApiResponse();
\Log::debug($response);
getApiResponce

function getApiResponse()
{
    $response = ApiController::getApi(); // ここまでは正常に動いていた
    return json_decode($response);
}

こんなふうにjson_decodeした結果をLogに出力しようとしていた。
その結果、Object of class stdClass could not be converted to string エラーが発生。

私はAPIからのレスポンス値が原因かと思って、返り値をログに出力したりして調べていたが、何時間かの格闘の末、Log出力自体に問題があることが判明した。

原因

laravelのLogは配列はそのまま渡しても出力してくれるが、オブジェクトは扱えない。
json_decodeの返り値は、デフォルトでオブジェクト形式となるため、それを出力しようとしてエラーとなってしまっていた。

結論

json_decodeで変換したオブジェクトを、そのままLog出力しようとして

Object of class stdClass could not be converted to string

になってしまった。

オブジェクトをLog出力したいときは、

\Log::debug(print_r($response, true));

のようにprint_rvar_dumpなどで出力してから、その結果(文字列)をログで出力するようにしよう。

16
10
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
10