当服务器返回 4xx 和 5xx 状态代码时,我想处理 Guzzle 的错误。我提出了这样一个请求
$client = $this->getGuzzleClient();
$request = $client->post($url, $headers, $value);
try {
$response = $request->send();
return $response->getBody();
} catch (\Exception $e) {
// How can I get the response body?
}
$e->getMessage
返回代码信息,但不返回 HTTP 响应的正文。如何获取响应正文?
根据 文档,可能需要捕获的异常类型有
GuzzleHttp\Exception\BadResponseException
(这是它们的超类)因此,处理此类错误的代码现在看起来像这样:
$client = new GuzzleHttp\Client;
try {
$client->get('http://google.com/nosuchpage');
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
}
根据 文档,您可以捕获相应的异常类型(4xx 错误为 ClientErrorResponseException
)并调用其 getResponse()
方法获取响应对象,然后在该对象上调用 getBody()
:
use Guzzle\Http\Exception\ClientErrorResponseException;
...
try {
$response = $request->send();
} catch (ClientErrorResponseException $exception) {
$responseBody = $exception->getResponse()->getBody(true);
}
向 getBody
函数传递 true
表示您希望获取字符串形式的响应体。否则,您将以 Guzzle\Http\EntityBody
类实例的形式获取响应体。
正如马克提到的,BadResponseException 只是 ClientException 和 ServerException 的超类。但 RequestException 也是 BadRequestException 的超类。这不仅能捕获 400 和 500 错误,还能捕获网络错误。所以,假设你请求下面的页面,但你的网络出现了问题,而你的捕获器期待的是 BadResponseException。那么你的应用程序就会抛出一个错误。
在这种情况下,最好是期待 RequestException 并检查响应。
try {
$client->get('http://123123123.com')
} catch (RequestException $e) {
// If there are network errors, we need to ensure the application doesn't crash.
// if $e->hasResponse is not null we can attempt to get the message
// Otherwise, we'll just pass a network unavailable message.
if ($e->hasResponse()) {
$exception = (string) $e->getResponse()->getBody();
$exception = json_decode($exception);
return new JsonResponse($exception, $e->getCode());
} else {
return new JsonResponse($e->getMessage(), 503);
}
}