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

如何在外层catch捕获fetch嵌套then中的错误?

解决方案

问题的核心是内层Promise链没有被返回给外层的then,导致错误无法传递到外层catch。以下是修正后的代码:

fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: this.enteredName,
    rating: this.chosenRating
  })
}).then(response => {
  if (response.ok) {
    //...
  } else {
    // 返回内层Promise链,让错误能向上冒泡到外层catch
    return response.json().then(json => {
      const msg = 'Custom error handling: could not save data' +
        ', error code: ' + response.status + ', error: ' + json.error;
      throw new Error(msg);
    });
  }
})
.catch(err => {
  console.log('catch2:');
  this.error = err.message;
});

关键说明

  • 返回内层Promise:在else块中返回response.json().then(...),让外层Promise链能感知到内层Promise的状态变化。当内层then中抛出错误时,这个Promise会变为rejected状态,错误会自动传递到外层的catch中。
  • 移除冗余内层catch:原代码中的内层catch仅做重新抛出错误的操作,没有额外处理逻辑,直接移除后错误会自然冒泡,代码更简洁。
  • 补充body序列化:原代码直接传入JavaScript对象作为body,fetch要求body必须是序列化后的字符串(或其他支持的类型),因此添加JSON.stringify()确保请求格式正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 06:32:19