GuzzleHttp 異常信息為什么會(huì)被截取?

當(dāng)我們?cè)谑褂眠@個(gè)擴(kuò)展包的時(shí)候,發(fā)送一些請(qǐng)求,當(dāng)請(qǐng)求出現(xiàn)問(wèn)題,就要去獲取他的異常,而當(dāng)我們使用下面的代碼時(shí),會(huì)發(fā)現(xiàn)異常會(huì)被截?cái)?/p>

 try{
    .
    .
    .
    $info = $response->getBody()->getContents();

    return $info;
}catch (\GuzzleHttp\Exception\RequestException $e){
    ErrorLogs($e->getMessage(),'exception');
}

最后當(dāng)捕獲到異常的時(shí)候,會(huì)出現(xiàn)下面這種現(xiàn)象

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

可以看到,這并不是完整的報(bào)錯(cuò)信息,因?yàn)樵谧铌P(guān)鍵的代碼排查處,出現(xiàn)了截取,截取的關(guān)鍵字就是truncated...,那么怎么獲取到完整的信息呢
這樣做

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

使用上面的代碼就可以獲取到完整報(bào)錯(cuò)信息

被截?cái)嗟脑际荊uzzle代碼里做了限制,來(lái)看Exception源碼,源碼來(lái)自文件

//.\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;
    }

所以當(dāng)$size超過(guò)了120個(gè)字符之后,就會(huì)用(truncated...)截取,當(dāng)然我們不希望去改動(dòng)GuzzleHttp的核心代碼,所以還是使用上面的方法來(lái)獲取完整的異常信息吧。

原文參考:

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容