Guzzle http 的 Laravel 中的错误日志记录被截断

问题描述 投票:0回答:4

Guzzle http 正在截断超过 120 个字符的异常,但我需要记录完整的异常消息。我该怎么做?

我正在使用 laravel 4.2.22。

laravel guzzle
4个回答
27
投票
try {
    // whatever
} catch (\GuzzleHttp\Exception\RequestException $ex) {
     return $ex->getResponse()->getBody()->getContents(); 
     // you can even json_decode the response like json_decode($ex->getResponse()->getBody()->getContents(), true)    
}

11
投票

Laravel 5 和 4 是一样的

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

如果你去

$ex->getMessage()
,你会得到
(truncated...)
在最后。


4
投票

可能是更好的解决方案:

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());
}

0
投票

完整的解决方案是在创建

'http_errors'
实例时替换
\GuzzleHttp\HandlerStack
中的
\GuzzleHttp\Client
中间件。例如,对于功能测试中的 Laravel 应用程序设置,我在每个测试的公共设置点执行此操作:

protected function dontTruncateGuzzleExceptions(Application $app): void {
    /** @var HandlerStack $handler */
    $app->bind(
        Client::class,
        function() {
            $stack = HandlerStack::create(); 
            $stack->before(
                'http_errors',
                Middleware::httpErrors(new BodySummarizer(2000000)),
                'http_errors_untruncated'
            );
            $stack->remove('http_errors');
            return new Client(['handler' => $stack]);
        }
    );
}

这是 Github 上的相关问题:https://github.com/guzzle/guzzle/issues/2185

© www.soinside.com 2019 - 2024. All rights reserved.