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

如何在Laravel捕获异常时获取HTTP请求的完整明细信息

解决方案

你使用的是Laravel框架的HTTP客户端,两类异常场景都可以直接通过异常实例获取完整请求信息,具体方法如下:

1. 异常内置的请求对象获取方法

Laravel HTTP客户端抛出的RequestException和ConnectionException都封装了请求相关数据:

  • RequestException:通常是接口返回4xx/5xx状态码时抛出,可直接调用$exception->getRequest()获取请求实例
  • ConnectionException:通常是网络连接失败、超时、DNS解析错误时抛出,同样支持调用$exception->getRequest()获取请求实例,部分旧版本可通过$exception->transferStats->getRequest()获取

你可以直接复用之前的Message::toString()方法格式化请求信息即可。

2. 改造后的代码示例

try {
    $request = json_encode($data);
    $result = $this->pendingRequest->{$method}('http://test.local/general/wallets/1000000', $data);
    // 此处可获取请求明细
    $request = $result->transferStats ? Message::toString($result->transferStats->getRequest()) : $request;
    $result->throw();
    $this->setLog($provider, $step, $request, $result->body(), $url, $result->status());
    return $result;
} catch (RequestException $exception) {
    // 获取请求明细
    $request = Message::toString($exception->getRequest());
    // 后续打日志逻辑,可按需获取异常响应信息
    $this->setLog($provider, $step, $request, $exception->response()?->body() ?? $exception->getMessage(), $url, $exception->getCode());
} catch (ConnectionException $exception) {
    // 获取请求明细
    $request = Message::toString($exception->getRequest());
    // 连接异常无响应,记录异常信息即可
    $this->setLog($provider, $step, $request, $exception->getMessage(), $url, $exception->getCode());
}

额外优化建议

如果需要全局统一记录请求异常日志,可以直接在HTTP客户端的withMiddleware方法里添加全局中间件,统一捕获记录所有请求和异常信息,不用在每个业务请求里重复写捕获逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:27:04