问题是:
当服务器返回 4xx 和 5xx 状态码时,我想处理来自 Guzzle 的错误
虽然您可以专门处理 4xx 或 5xx 状态代码,但实际上捕获所有异常并相应地处理结果是有意义的。
问题也是,您是只想处理错误还是获取正文?我认为在大多数情况下,处理错误而不获取消息正文或仅在非错误的情况下获取正文就足够了。
我会查看文档以检查您的 Guzzle 版本如何处理它,因为这可能会改变:https ://docs.guzzlephp.org/en/stable/quickstart.html#exceptions
另请参阅有关“处理错误”的官方文档中的此页面,其中指出:
收到 4xx 或 5xx 响应的请求将抛出Guzzle\Http\Exception\BadResponseException
. 更具体地说,4xx错误会抛出 a Guzzle\Http\Exception\ClientErrorResponseException
,而5xx错误会抛出 Guzzle \Http\Exception\ServerErrorResponseException
。您可以捕获特定异常或仅捕获BadResponseException
处理任一类型的错误。
Guzzle 7(来自文档):
. \RuntimeException
└── TransferException (implements GuzzleException)
└── RequestException
├── BadResponseException
│ ├── ServerException
│ └── ClientException
├── ConnectException
└── TooManyRedirectsException
因此,您的代码可能如下所示:
try {
$response = $client->request('GET', $url);
if ($response->getStatusCode() >= 300) {
// is HTTP status code (for non-exceptions)
$statusCode = $response->getStatusCode();
// handle error
} else {
// is valid URL
}
} catch (TooManyRedirectsException $e) {
// handle too many redirects
} catch (ClientException | ServerException $e) {
// ClientException - A GuzzleHttp\Exception\ClientException is thrown for 400 level errors if the http_errors request option is set to true.
// ServerException - A GuzzleHttp\Exception\ServerException is thrown for 500 level errors if the http_errors request option is set to true.
if ($e->hasResponse()) {
// is HTTP status code, e.g. 500
$statusCode = $e->getResponse()->getStatusCode();
}
} catch (ConnectException $e) {
// ConnectException - A GuzzleHttp\Exception\ConnectException exception is thrown in the event of a networking error. This may be any libcurl error, including certificate problems
$handlerContext = $e->getHandlerContext();
if ($handlerContext['errno'] ?? 0) {
// this is the libcurl error code, not the HTTP status code!!!
// for example 6 for "Couldn't resolve host"
$errno = (int)($handlerContext['errno']);
}
// get a description of the error (which will include a link to libcurl page)
$errorMessage = $handlerContext['error'] ?? $e->getMessage();
} catch (\Exception $e) {
// fallback, in case of other exception
}
如果你真的需要身体,你可以像往常一样检索它:
https://docs.guzzlephp.org/en/stable/quickstart.html#using-responses
$body = $response->getBody();