Client发送一些请求,当返回状态不是200的时候,无法获取完整错误信息
$client = new Client([
'base_uri' => $this->getUri().'/order/aaaaaa',
'timeout' => 30,
'verify' => false
]);
try {
$response = $client->request('POST', '', [
'headers' => [
'Lang'=>'zh-CN',
'Authorization' => 'Bearer ' . $accessToken
],
'json' =>[
'channelCode' => '',
'exportId' => '',
]
]);
$response = $response->getBody()->getContents();
return $this->success('登录成功', collect([]));
} catch (GuzzleException $e) {
dd($e->getResponse()->getBody()->getContents());
return $this->error($e->getMessage(), collect([]));
}
最后当捕获到异常的时候,会出现下面这种现象
Client error: `POST http://192.168.11.1/api/order/aqedd` resulted in a `422 Unprocessable Content` response:
{"success":false,"code":422,"locale":"zh-CN","message":"给定的数据不能为空","data":{"channelCode":["channel cod (truncated...)
可以看到,这并不是完整的报错信息,因为在最关键的代码排查处,出现了截取,截取的关键字就是truncated...
,那么怎么获取到完整的信息呢
这样做
dd($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的核心代码,所以还是使用上面的方法来获取完整的异常信息吧。