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

如何捕获404响应并控制程序流程?got库catch未触发排查

问题解答

你的疑问不成立——404响应在got库中默认会被抛出HTTPError,但你的代码没捕获到错误是因为代码结构错误,和404是否被视为错误无关。

错误原因分析

  • 你的try/catch包裹的是callFirstAPI函数的定义,不是函数的异步执行过程。异步函数执行时产生的错误,根本不会被这个外层的try/catch捕获。
  • 调用callFirstAPI()时,没有用await或者.catch()处理它返回的Promise,导致错误变成了未捕获的Promise拒绝,自然不会进入你写的catch块。

正确实现代码

写法1:在函数内部捕获错误

async function callFirstAPI() {
  try {
    const response = await got(url, options).json();
    console.log(response);
    // 成功时的处理逻辑
  } catch (error) {
    // 判断是否是404错误
    if (error.response?.status === 404) {
      console.log("第一个API返回404,调用备用API");
      await callBackupAPI();
    } else {
      // 处理其他错误
      console.error("调用第一个API出错:", error);
    }
  }
}

// 调用函数
callFirstAPI();

写法2:在函数调用处捕获错误

async function callFirstAPI() {
  const response = await got(url, options).json();
  console.log(response);
  // 成功时的处理逻辑
}

async function main() {
  try {
    await callFirstAPI();
  } catch (error) {
    if (error.response?.status === 404) {
      console.log("第一个API返回404,调用备用API");
      await callBackupAPI();
    } else {
      console.error("调用第一个API出错:", error);
    }
  }
}

// 执行主逻辑
main();

补充说明

  • got库默认会对所有4xx、5xx状态码的响应抛出HTTPError,错误对象里的response.status就是HTTP状态码,无需解析日志的textPayload。
  • 所有包含await的代码必须放在async函数内部,否则会触发语法错误。

内容的提问来源于stack exchange,提问作者Thomas David Kehoe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:40:31