美文网首页Laravel备忘录
GuzzleHttp 异常信息为什么会被截取?

GuzzleHttp 异常信息为什么会被截取?

作者: 提莫小小队长 | 来源:发表于2018-08-13 15:00 被阅读7次

    当我们在使用这个扩展包的时候,发送一些请求,当请求出现问题,就要去获取他的异常,而当我们使用下面的代码时,会发现异常会被截断

     try{
        .
        .
        .
        $info = $response->getBody()->getContents();
    
        return $info;
    }catch (\GuzzleHttp\Exception\RequestException $e){
        ErrorLogs($e->getMessage(),'exception');
    }
    
    

    最后当捕获到异常的时候,会出现下面这种现象

    {"message":"Unable to read image from path (\/tmp\/php9tgESo).","status_code":500,"debug":{"line":26,"file":"\/wwwroot\/default (truncated...)
    
    

    可以看到,这并不是完整的报错信息,因为在最关键的代码排查处,出现了截取,截取的关键字就是truncated...,那么怎么获取到完整的信息呢
    这样做

    //var_dump($e->getResponse()->getBody()->getContents());
    

    使用上面的代码就可以获取到完整报错信息

    被截断的原始是Guzzle代码里做了限制,来看Exception源码,源码来自文件

    //.\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php
    public static function getResponseBodySummary(ResponseInterface $response)
        {
            $body = $response->getBody();
    
            if (!$body->isSeekable()) {
                return null;
            }
    
            $size = $body->getSize();
    
            if ($size === 0) {
                return null;
            }
    
            $summary = $body->read(120);
            $body->rewind();
    
            if ($size > 120) {
                $summary .= ' (truncated...)';
            }
    
            // Matches any printable character, including unicode characters:
            // letters, marks, numbers, punctuation, spacing, and separators.
            if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/', $summary)) {
                return null;
            }
    
            return $summary;
        }
    

    所以当$size超过了120个字符之后,就会用(truncated...)截取,当然我们不希望去改动GuzzleHttp的核心代码,所以还是使用上面的方法来获取完整的异常信息吧。

    原文参考:

    https://laracasts.com/discuss/channels/general-discussion/guzzle-error-message-gets-truncated?page=1
    https://stackoverflow.com/questions/41293050/error-log-truncated-in-laravel-5-3

    相关文章

      网友评论

        本文标题:GuzzleHttp 异常信息为什么会被截取?

        本文链接:https://www.haomeiwen.com/subject/hfhubftx.html