本文详解如何正确捕获 guzzle http 客户端抛出的各类异常(如 clientexception、requestexception),提取错误信息并统一返回结构化字符串或数组,避免直接返回异常对象导致调用方无法解析。
在使用 Guzzle 调用 Twitter API(或其他 RESTful 服务)时,$lists->get($list_id, $params) 等方法内部发起 HTTP 请求,一旦失败(如网络超时、404、401、500 等),Guzzle 不会静默失败,而是抛出继承自 \GuzzleHttp\Exception\TransferException 的具体异常类。常见误区是仅 catch (\GuzzleHttp\Exception\ClientException $e) ——该异常仅覆盖 HTTP 4xx 状态码(如 400、401、404),而忽略 5xx 服务器错误(由 ServerException 抛出)和网络层问题(如 DNS 失败、连接超时,由 RequestException 或 ConnectException 抛出)。
因此,要真正“捕获所有 Guzzle 异常并返回可用错误信息”,需按异常继承层级合理捕获:
以下是推荐的健壮写法(已优化可读性与实用性):
public static function get_list($list_id)
{
$lists = self::get_lists();
$params = [
'list.fields' => 'creat
ed_at,follower_count,member_count,private,description,owner_id',
'user.fields' => 'created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld'
];
try {
$response = $lists->get($list_id, $params);
// 确保响应为 200 OK 并成功解析 JSON
if ($response->getStatusCode() === 200) {
return json_decode($response->getBody()->getContents(), true);
}
// 非 200 但未被异常捕获的情况(极少见,取决于客户端配置)
return [
'error' => 'Unexpected HTTP status code',
'status_code' => $response->getStatusCode(),
'body' => (string) $response->getBody()
];
} catch (\GuzzleHttp\Exception\ClientException $e) {
return self::formatGuzzleError($e, 'Client error');
} catch (\GuzzleHttp\Exception\ServerException $e) {
return self::formatGuzzleError($e, 'Server error');
} catch (\GuzzleHttp\Exception\RequestException $e) {
return self::formatGuzzleError($e, 'Network or request error');
} catch (\Exception $e) {
// 捕获其他非-Guzzle 异常(如 JSON 解析失败、空响应等)
return [
'error' => 'Unexpected application error',
'message' => $e->getMessage(),
'code' => $e->getCode()
];
}
}
// 提取共用逻辑,便于维护与日志扩展
private static function formatGuzzleError(\GuzzleHttp\Exception\RequestException $e, string $type): array
{
$error = [
'error' => $type,
'message' => $e->getMessage(),
'request_url' => (string) $e->getRequest()->getUri(),
'request_method' => $e->getRequest()->getMethod(),
];
if ($e->hasResponse()) {
$response = $e->getResponse();
$error['response_status'] = $response->getStatusCode();
$error['response_body'] = (string) $response->getBody();
} else {
$error['response_status'] = null;
$error['response_body'] = 'No response received (e.g., timeout, connection refused)';
}
return $error;
}✅ 关键改进说明:
⚠️ 注意事项:
通过以上方式,你不仅能稳定捕获所有 Guzzle 异常,还能输出清晰、一致、可编程解析的错误结构,大幅提升 API 客户端的健壮性与可观测性。