Skip to content

错误处理 ​

概述 ​

HTTP 客户端模块把请求期间的失败统一收敛为 kuiper\http\client\HttpClientException(继承 \RuntimeException):连接失败、4xx/5xx 响应、传输层错误都不会以原始 Guzzle 异常类型逃逸到业务代码。原始异常保留在异常链上,响应内容可通过便捷方法获取。

HttpClientException ​

php
<?php

declare(strict_types=1);

namespace kuiper\http\client;

use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\ResponseInterface;

class HttpClientException extends \RuntimeException
{
    public function __construct(string $message = '', ?\Throwable $previous = null);

    public function getResponse(): ?ResponseInterface;

    public function getStatusCode(): ?int;
}
方法说明
getPrevious()原始 Guzzle 异常(ConnectException / RequestException / TransferException)
getResponse()原始 HTTP 响应;从 RequestException 中提取,连接失败等没有响应的异常返回 null
getStatusCode()HTTP 状态码;没有响应时返回 null

异常的 exception code 固定为 0,错误信息按失败类别带不同前缀(见下表),便于日志检索。

异常的来源与包装 ​

代理方法调用(HttpRpcExecutorFactory::invoke())捕获三类 Guzzle 异常并包装:

Guzzle 异常触发场景包装后的消息
ConnectException建连失败(超时、DNS 解析失败、连接被拒)Failed to connect: {原因}
RequestException请求收发失败,包括服务端返回 4xx / 5xx(http_errors 默认开启)HTTP request failed: {原因}
TransferException其他传输错误(如响应 body 回读失败)——前两类之外的兜底,避免原始类型逃逸HTTP transfer failed: {原因}
php
<?php

declare(strict_types=1);

namespace App\Service;

use App\Client\GithubApi;
use kuiper\http\client\HttpClientException;

class UserSyncService
{
    public function __construct(
        private readonly GithubApi $githubApi
    ) {
    }

    public function sync(string $username): void
    {
        try {
            $user = $this->githubApi->getUser($username);
        } catch (HttpClientException $e) {
            $status = $e->getStatusCode();
            if (404 === $status) {
                // 用户不存在:业务语义,不重试
                return;
            }
            if (null !== $status && $status >= 500) {
                // 服务端错误:可重试
                throw $e;
            }

            // 连接失败等:看原始异常
            $previous = $e->getPrevious();
            throw $e;
        }
    }
}

状态码语义 ​

默认配置下 Guzzle 的 http_errors 选项开启,4xx / 5xx 响应会抛异常,业务代码拿不到非 2xx 的响应对象——需要检查响应体时通过 HttpClientException::getResponse():

php
<?php

declare(strict_types=1);

try {
    $result = $api->getUser('alice');
} catch (HttpClientException $e) {
    $response = $e->getResponse();
    if (null !== $response) {
        $body = (string) $response->getBody();   // 错误响应体(如 API 的 error json)
        $code = $response->getStatusCode();      // 4xx / 5xx
    }
}

客户端选项是标准 Guzzle 选项,需要业务侧自行处理 4xx 响应时,可以在组件级配置里关闭:application.http_client.{组件类名} 加 'http_errors' => false(见配置指南)。

关闭 http_errors 后 4xx / 5xx 不再抛异常,代理照常把响应体按方法返回类型反序列化——比如返回类型是 array 时,404 的 JSON 响应体解码后直接得到 ['message' => 'Not Found'],而不是 Response 对象。需要在业务层分辨失败与否时,把方法返回类型声明为 \Psr\Http\Message\ResponseInterface(代理原样返回响应),或保持默认的异常语义用 HttpClientException::getResponse() 取错误响应。

重试 ​

retry 选项在 handler 栈上加 Guzzle Middleware::retry。内置的判定器(HttpClientFactory::createRetryCallback())只重试两类失败:

  1. 连接失败(ConnectException)——请求尚未发出,重试幂等安全
  2. 5xx 响应——服务端错误

4xx 客户端错误不重试。达到最大重试次数(retries >= maxRetries)后停止。重试期间每次失败抛出的仍是最后一次的 HttpClientException。

php
<?php

declare(strict_types=1);

// src/config.php —— 失败最多重试 3 次(连接失败或 5xx)
return [
    'application' => [
        'http_client' => [
            'default' => [
                'retry' => 3,
            ],
        ],
    ],
];

需要自定义重试策略(例如按 Retry-After 头退避)时传 callable:

php
<?php

declare(strict_types=1);

// src/config.php —— middleware/retry 的 callable 形式
return [
    'application' => [
        'http_client' => [
            'default' => [
                'retry' => function ($retries, $request, $response = null, $exception = null) {
                    return $retries < 3 && null !== $response && $response->getStatusCode() === 429;
                },
            ],
        ],
    ],
];

callable 形式只支持 application.http_client.* 配置(环境变量只能表达数字次数)。

空响应体 ​

声明了返回类型的方法收到空响应体(204 等)时:

  • 返回类型是 void / never,或方法没有声明返回类型:返回 null
  • 其他非空返回类型(如 User、array):抛 UnexpectedValueException,消息含方法名与声明的返回类型——比调用方收到 TypeError 更容易定位

相关页面 ​

基于 MIT 许可发布