Search code examples
phpguzzleguzzle6

How I get body from guzzle6 exception


So I have the following code

    try {
        $response = $client->request('POST', 'http://dev.api.example.com/v1/partners', [
            // params
        ]);
    } catch (ClientException $ex) {
        Debug::dump($ex);
        die;
    }

Now I am sending bad data on purpose for testing and the api send a 400 code since there is something missing and I am catching it with the try and catch block. Now I want to show the body the the api returns. I have tried the following

$ex->getResponse()->getBody()

But all it returns is the following.

GuzzleHttp\Psr7\Stream Object
(
    [stream:GuzzleHttp\Psr7\Stream:private] => Resource id #73
    [size:GuzzleHttp\Psr7\Stream:private] => 
    [seekable:GuzzleHttp\Psr7\Stream:private] => 1
    [readable:GuzzleHttp\Psr7\Stream:private] => 1
    [writable:GuzzleHttp\Psr7\Stream:private] => 1
    [uri:GuzzleHttp\Psr7\Stream:private] => php://temp
    [customMetadata:GuzzleHttp\Psr7\Stream:private] => Array
        (
        )

)

While the api sends this in postment

{
  "success": false,
  "error": {
    "code": 400,
    "message": "The name has already been taken.<br />The email field is required."
  }
}

Solution

  • Okay I have figured it out. All you need to do is do the following in the exception.

    $ex->getResponse()->getBody()->getContents()

    As of

    http://docs.guzzlephp.org/en/latest/psr7.html