You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中如何捕获接口调用返回的504 Gateway Timeout异常

解决504超时无法被try-catch捕获的问题

原因分析

你的代码仅捕获Exception类,但实际场景中504错误未被捕获通常有两种情况:

  1. 所使用的客户端库默认不会将HTTP 504状态码转化为异常抛出,而是返回包含错误信息的响应对象;
  2. 客户端抛出的是Error或其他Throwable子类,Exception作为基类无法覆盖所有可抛出类型。

解决方案

方案1:捕获所有可抛出类型

将catch块改为捕获Throwable(PHP中所有可抛出对象的顶层基类),覆盖Exception和Error:

try
{
    $response = $client->chat()->create([
        'model' => $model,
        'messages' => [
            ['role' => 'user', 'content' => $prompt],
        ],
        'temperature' => $temperature,
        'max_tokens' => $max_tokens,
        'top_p' => $top_p,
        'frequency_penalty' => $frequency_penalty,
        'presence_penalty' => $presence_penalty
    ]);

    $answer = trim($response['choices'][0]['message']['content']);
}
catch (Throwable $e)
{
    $answer = "Timed Out, try again";
}

方案2:手动检查响应状态码

如果客户端库默认返回错误响应而非抛出异常,需手动校验状态码:

$response = $client->chat()->create([
    // 保持原有参数配置
]);

// 判断是否为504超时
if ($response->getStatusCode() === 504) {
    $answer = "Timed Out, try again";
} else {
    $answer = trim($response['choices'][0]['message']['content']);
}

方案3:配置客户端开启异常抛出(以OpenAI客户端为例)

多数PHP HTTP客户端支持配置将HTTP错误转化为异常,比如OpenAI客户端可开启http_errors参数:

// 初始化客户端时开启HTTP错误抛出
$client = OpenAI::client('your-api-key', [
    'http_errors' => true,
]);

// 后续正常使用try-catch捕获
try {
    // 原有请求代码
} catch (Exception $e) {
    $answer = "Timed Out, try again";
}

额外优化

若需精准区分504和其他异常,可针对性捕获特定异常类(如Guzzle的RequestException):

catch (RequestException $e) {
    if ($e->getResponse() && $e->getResponse()->getStatusCode() === 504) {
        $answer = "Timed Out, try again";
    } else {
        $answer = "请求失败:" . $e->getMessage();
    }
} catch (Throwable $e) {
    $answer = "发生错误:" . $e->getMessage();
}

内容的提问来源于stack exchange,提问作者anjanesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 05:32:42