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

JavaScript中fetch链式调用的response.status错误处理问题

我来帮你梳理下问题出在哪,以及怎么解决:

问题根源

你的代码有两个核心问题:

  • 函数f使用了await但未声明为async,这会直接触发语法错误;
  • 第一个.then()里,当状态码为200时,你没有把response对象返回给后续的链式调用,导致下一个.then(response => response.json())拿到的参数是undefined,调用.json()自然会失败。

修复方案

方案1:修正链式调用逻辑

function f(path) { 
  return fetch(path) 
    .then(response => { 
      if (response.status !== 200) { 
        // 建议抛出带详细信息的Error,而非直接抛状态码,便于后续排查
        throw new Error(`请求失败,状态码:${response.status}`);
      }
      // 关键:将response返回,传递给下一个then
      return response;
    }) 
    .then(response => response.json()) 
    .then(parsedData => { 
      // 在这里处理解析后的JSON数据
      console.log("解析完成的数据:", parsedData);
    }) 
    .catch(error => { 
      console.error("错误信息:", error.message || error);
    });
}

方案2:改用async/await(可读性更高)

如果你觉得链式调用嵌套麻烦,更推荐用async/await写法:

async function f(path) { 
  try {
    const response = await fetch(path);
    if (response.status !== 200) {
      throw new Error(`请求失败,状态码:${response.status}`);
    }
    const parsedData = await response.json();
    // 处理解析后的JSON数据
    console.log("解析完成的数据:", parsedData);
  } catch (error) {
    console.error("错误信息:", error.message || error);
  }
}

补充说明

你之前的代码里,第一个.then()在状态码正常时没有返回response,导致该then的返回值是undefined,后续的then就会拿undefined去调用.json(),这才是触发错误的直接原因。另外,直接抛出状态码不利于错误信息的可读性,包装成Error对象会更友好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 19:33:11