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

Laravel中捕获Stichoza GoogleTranslate的RateLimitException及代理问题排查

问题解答

一、RateLimitException捕获方式的正确性

你写的try-catch逻辑方向是对的,但要注意必须指定完整的异常命名空间——RateLimitException是Stichoza库的专属异常类,直接写类名PHP会无法识别。

可以用两种方式修正:

  1. 先引入命名空间再捕获:
use Stichoza\GoogleTranslate\Exceptions\RateLimitException;

function translate($tr,$text,$target,$source='en-GB') {
    try {
        $trans = $tr->setSource($source)->setTarget($target)->translate($text);
    } catch (RateLimitException $e) {
        report($e); // 把异常记录到Laravel日志
        $trans = GoogleCloudTranslation($text); // 切换到Google Cloud翻译
        // 若Cloud翻译未实现,可临时返回原文本:$trans = $text;
    }
    return $trans;
}
  1. 直接在catch中写完整命名空间:
function translate($tr,$text,$target,$source='en-GB') {
    try {
        $trans = $tr->setSource($source)->setTarget($target)->translate($text);
    } catch (\Stichoza\GoogleTranslate\Exceptions\RateLimitException $e) {
        report($e);
        $trans = GoogleCloudTranslation($text);
    }
    return $trans;
}

二、代理cURL错误7的解决

错误提示“Unsupported proxy scheme”是因为你用了tcp://作为代理协议头,curl不支持该格式,换成http://或https://即可,示例:

$trans = $tr->setOptions(['proxy' => 'http://localhost:8090'])
            ->setSource($source)
            ->setTarget($target)
            ->translate($text);

如果是socks5类型代理,就写成socks5://localhost:8090,根据实际代理类型调整协议头。

三、完整容错逻辑实现

结合你的需求,最终的translate函数可以写成这样:优先用Stichoza,触发限流异常时切换到Google Cloud翻译,所有翻译都失败时兜底返回原文本:

use Stichoza\GoogleTranslate\Exceptions\RateLimitException;
use Stichoza\GoogleTranslate\Exceptions\GoogleTranslateException; // 额外捕获其他翻译异常

function translate($tr,$text,$target,$source='en-GB') {
    try {
        return $tr->setSource($source)->setTarget($target)->translate($text);
    } catch (RateLimitException $e) {
        report($e);
        // 尝试Google Cloud翻译
        try {
            return GoogleCloudTranslation($text, $source, $target); // 注意传入源语言和目标语言参数
        } catch (\Exception $cloudE) {
            report($cloudE);
            return $text; // Cloud翻译失败时返回原文本
        }
    } catch (GoogleTranslateException $e) {
        // 捕获Stichoza的其他异常(如网络错误、参数错误等)
        report($e);
        return $text;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 12:07:44