tabimoba.net

とあるエンジニアの雑記帳

Guzzleでリクエスト先から返されたエラーメッセージをtruncateさせずに取得する

Guzzleでリクエスト先からエラーが返された際、そのメッセージがtruncateされてしまい、不都合な場合があります。今回は、このメッセージをtruncateされない状態で取得してみます。

PHP Fatal error:  Uncaught GuzzleHttp\Exception\ServerException: Server error: `POST https://hoge.local/upload` resulted in a `500 Internal Server Error` response:
{"error":{"code":500,"message":"\u30a2\u30c3\u30d7\u30ed\u30fc\u30c9\u3059\u308b\u30d5\u30a1\u30a4\u30eb\u3092\u9078\u62 (truncated...)
 in /hoge/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113

対応方法

次のコードのように、catch側に $e->getResponse()->getBody()->getContents() を書くことで取得することが可能です。

コード

try {
        $res = $client->request('POST', $url, [
            ・・・
        ]);
} catch (Exception $e) {
        var_dump(json_decode($e->getResponse()->getBody()->getContents()));
}

結果

object(stdClass)#10 (1) {
  ["error"]=>
  object(stdClass)#34 (2) {
    ["code"]=>
    int(500)
    ["message"]=>
    string(67) "アップロードするファイルを選択してください。"
  }
}