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

API返回500等错误时fetch的catch块不触发,反而执行then块是什么原因?

核心问题原因
  • fetch API的设计规则是仅当网络层面请求失败时才会触发catch回调,例如断网、跨域被拦截、DNS解析失败等场景。HTTP状态码返回4xx、5xx时,fetch会判定为请求成功完成,默认不会进入catch块。
  • 你的代码未对响应的HTTP状态做校验,拿到response后直接调用response.json()解析响应体,无论返回200还是500都会走入后续的then回调处理结果。
  • 原代码存在语法遗漏:第二个then分支的else代码块结束后缺少闭合的},极端场景下可能引发非预期的执行逻辑。
修复方案

在第一个then回调中新增状态码校验逻辑,当响应状态不在200~299区间时主动抛出错误,即可触发后续的catch逻辑,修复后的代码如下:

const startHandler = () => {
    setOpenLoadingModal(true);
    fetch(url, {
      method: 'post',
      body: JSON.stringify(payload),
      headers: headers,
    })
      .then((response) => {
        // 校验HTTP响应状态
        if (!response.ok) {
          throw new Error(`请求异常,状态码:${response.status}`)
        }
        return response.json()
      })
      .then((result) => {
        console.log("🚀 ~ file: index.js ~ line 159 ~ .then ~ result", result)
        const { client_id, token } = result;
        if (!token || !client_id){
          setOpenErrorModal(true);
          return setOpenLoadingModal(false);
        } else{
          return history.push({
            pathname: FORMS_URL.LANDING_PAGE,
          });
        }
      })
      .catch((err) => {
        console.log(err)
        setOpenErrorModal(true);
        setOpenLoadingModal(false);
      });
  };

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 04:27:04