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

Laravel HTTP客户端重试时获取status()功能异常

环境信息
  • Laravel版本:10.35.0
  • PHP版本:8.1.26
  • 数据库驱动及版本:Mysql 5.7
问题描述

使用Laravel HTTP客户端的retries功能时,尝试从异常中获取响应状态码抛出错误,无法正常获取。

复现步骤
  • 通过HTTP客户端向不存在的域名(如sdfsd.com)发起GET请求
  • 按以下方式实现retries方法:
$client = $client->retry(3, 100, function (Exception $exception, PendingRequest $request) {
    Log::debug('foo');
    Log::debug($exception->response->status()); // 此行报错
    Log::debug('bar'); // 永远无法执行到这里

    return true;
});
报错信息

Undefined property: Illuminate\Http\Client\ConnectionException::$response

执行后仅能看到foo日志,bar日志无法输出。


解决方案

这并非文档错误或功能问题,核心原因是Laravel HTTP客户端抛出的异常类型不同,并非所有异常都带有response属性:

  • 当请求因域名不存在、网络中断等原因无法建立连接时,抛出的是ConnectionException,这类场景下根本没有收到服务器响应,自然不存在response对象。
  • 只有当服务器正常返回HTTP响应(哪怕是4xx、5xx错误状态码)时,抛出的RequestException才包含response属性,此时才能通过$exception->response->status()获取状态码。

正确的处理方式是先判断异常类型,再针对性处理:

$client = $client->retry(3, 100, function (Exception $exception, PendingRequest $request) {
    Log::debug('foo');
    
    if ($exception instanceof \Illuminate\Http\Client\RequestException) {
        Log::debug($exception->response->status());
    } else {
        Log::debug('请求连接失败:' . $exception->getMessage());
    }
    
    Log::debug('bar');

    return true;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 06:23:18