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

fetch请求返回400等错误状态码时Promise未reject、不触发catch如何解决

问题根因

这是fetch API 本身的设计规则导致的:

  • fetch 仅在网络请求无法发出(比如断网、跨域配置不合法、DNS解析失败等)时才会reject Promise,触发catch或者then的第二个错误回调
  • 只要请求成功到达服务器并返回响应,不管HTTP状态码是4xx还是5xx,都会判定为请求成功,走then的正常回调

解决方法

你需要在then的正常回调里手动判断响应的HTTP状态码是否符合预期,常用的判断方式是检查response.ok属性(状态码处于200~299区间时该值为true),如果不符合预期就手动抛出错误触发后续的catch逻辑。

改后代码示例:

await fetch("http://localhost:3000/login", {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    login: name,
    password: pass
  }),
})
.then(async (response) => {
  // 手动判断状态码是否合法
  if (!response.ok) {
    // 抛出错误,会进入后续catch
    throw new Error(`请求错误,状态码:${response.status}`)
  }
  await AsyncStorage.setItem('Login', name)
})
.catch(err => alert(err));

如果需要获取接口返回的错误提示内容,可以先解析响应体再抛出错误,比如你接口返回JSON格式的错误信息:

.then(async (response) => {
  if (!response.ok) {
    const errRes = await response.json()
    throw new Error(errRes.message || `请求错误,状态码:${response.status}`)
  }
  await AsyncStorage.setItem('Login', name)
})

内容的提问来源于stack exchange,提问作者King Of Chads

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:42:01