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

Laravel Http请求遇错误不退出,无需try/catch实现响应全记录

在Laravel中处理Http客户端错误状态码(无需try/catch)

要让Http请求在第三方API返回4xx/5xx状态码时不中断程序执行,核心是禁用Laravel Http客户端的自动异常抛出机制,具体实现如下:

修改请求代码

在原请求链中添加throw(false)方法,阻止客户端在遇到错误状态码时自动抛出异常:

$response = Http::timeout(10)
             ->retry(3, 1000)
             ->withToken($token)
             ->asJson()
             ->acceptJson()
             ->baseUrl('blabla.com')
             ->throw(false) // 关键:禁用自动抛出异常
             ->get('/get');

// 无论请求成功或失败,都会执行这里的日志记录
LogClass::logRequest([
    'url' => 'blabla.com/get',
    'status' => $response->status(),
    'response' => $response->body(),
    'request_data' => $response->request()->all()
]);

关键说明

  • throw(false):该方法会告诉Http客户端,即使收到4xx/5xx状态码,也不抛出RequestException异常,程序会继续执行后续代码。
  • 后续可通过$response->status()获取响应状态码,$response->successful()判断是否为2xx状态码,$response->failed()判断是否为4xx/5xx状态码,按需做额外逻辑处理。

替代方案(使用withOptions)

也可以通过设置客户端选项http_errors为false来达到同样效果:

$response = Http::timeout(10)
             ->retry(3, 1000)
             ->withToken($token)
             ->asJson()
             ->acceptJson()
             ->baseUrl('blabla.com')
             ->withOptions(['http_errors' => false]) // 禁用自动异常
             ->get('/get');

// 执行日志记录
LogClass::logRequest(...);

这样不管第三方API返回什么状态码,程序都不会中断,日志记录代码能稳定执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 22:47:11