Pragmatism in the real world

Increase truncated body in a Guzzle exception

When Guzzle throws BadResponseException, the message includes information about the method, URL response code and then a truncated part of the body.

For example:

"Client error: `GET https://dev.clientproject.com:4444/oauth2/authorize?client_id=983e98d2fab8756a&scope=scope&response_type=code&redirect_uri=%2Fhome&code_challenge=some_code_challenge_here` resulted in a `400 Bad Request` response:
{"error":"invalid_request","error_description":"The request is missing a required parameter, includes an invalid parame (truncated...)

To retrieve the full text of the body, you grab it from the response property of the exception:

$body = $e->getResponse()->getBody()->getContents();

Changing the truncation limit

If you want more text in the exception message you need to pass a handler stack to the Client‘s constructor with an httpErrors middleware that has a BodySummarizer with a larger truncation limit.

The easiest way to do this is to create the default stack and then modify it:

use GuzzleHttp\BodySummarizer;
use GuzzleHttp\HandlerStack;

// ...

$stack = HandlerStack::create();
$stack->remove('http_errors');
$stack->unshift(Middleware::httpErrors(new BodySummarizer(1500)), 'http_errors');

Set the number of characters to truncate at in the BodySummarizer‘s constructor. I picked 1500; the default is 120 (as of this time of writing).

After creating the stack, we remove the current httpErrors middleware and add a new one. Note that it needs to be first in the stack as we want it to handle any error from any subsequent middleware too.

We then create our client with our custom stack:

use GuzzleHttp\Client;

// ...

$this->client = new Client([
    'handler'  => $stack,
    'base_uri' => $this->baseUri,
]);

That’s it. There’s now more text in the BadResponseException message.