3

Guzzle http is truncating exceptions with more than 120 characters, but I need to log the full exception message. How can I do this?

I am using laravel 4.2.22.

Yevgeniy Afanasyev
  • 27,544
  • 16
  • 134
  • 147
Parvez Alam
  • 120
  • 2
  • 11

2 Answers2

5

It is the same for Laravel 5 and 4

    try {
        $response = $client->post($path, $params);
    } catch (\GuzzleHttp\Exception\RequestException $ex) {
        \Log::debug('error');
        \Log::debug((string) $ex->getResponse()->getBody());
        throw $ex;
    }

if you just go to $ex->getMessage(), you will get (truncated...) at the end.

Yevgeniy Afanasyev
  • 27,544
  • 16
  • 134
  • 147
  • The Exception to capture should be `GuzzleHttp\Exception\RequestException` and not the raw `Exception`, that way it'll auto-complete correctly and not catch errors which would make the methods above fail. – Elven Spellmaker Apr 15 '20 at 19:49
  • 1
    Can you please explain, what would "auto-complete correctly" and how can "the methods above fail"? – Yevgeniy Afanasyev Apr 16 '20 at 00:32
  • Sure, basically the `getResponse()` method isn't part of the standard methods available for the `Exception` class. It's an extension made by Guzzle. If an Exception happened to be thrown that wasn't of the type that had the method you'd get a method not found Exception. In terms of auto complete when you capture the correct error an IDE knows what methods are available and will suggest getResponse in the list of available methods. – Elven Spellmaker Apr 16 '20 at 06:33
  • 1
    Thank you. You are right, this code would create unexpected exception depressing. I've changed the code. – Yevgeniy Afanasyev Apr 17 '20 at 02:01
0

Might be better solution:

try {
    // do request here like:
    // return $client->post($path, $params);
} catch (\GuzzleHttp\Exception\ServerException $ex) {
    $exFactoryWithFullBody = new class('', $ex->getRequest()) extends \GuzzleHttp\Exception\RequestException {
        public static function getResponseBodySummary(ResponseInterface $response)
        {
            return $response->getBody()->getContents();
        }
    };

    throw $exFactoryWithFullBody->create($ex->getRequest(), $ex->getResponse());
}
mvorisek
  • 2,758
  • 1
  • 12
  • 46