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

如何使用Fetch API读取500状态码响应的响应体内容

解决Fetch API读取500响应体内容的问题

问题核心在于:Fetch API的响应体读取方法(比如text()、json())都是异步操作,直接访问response.body无法拿到解析后的内容,必须调用对应解析方法并等待其执行完成。

修改你的代码如下,针对500状态的响应做异步读取处理:

return fetch(url, options)
.then((response) => {
  if(response.status === 200){ 
    return response.text();
  } 
  else if(response.status === 500){
    // 根据后端返回的格式选择text()或json()
    return response.text().then(errorContent => {
      // 弹出自定义错误提示
      alert(errorContent);
      // 可选:将错误抛到catch块统一处理
      throw new Error(errorContent);
    });
  }
  // 处理其他非200/500的异常状态码
  else {
    return response.text().then(otherMsg => {
      throw new Error(`请求失败:${otherMsg}`);
    });
  }
})
.catch((error) => {
 throw error;
})

额外注意

  • 如果后端返回的是JSON格式错误信息(例如{"errorMsg":"文件下载失败"}),把response.text()替换为response.json(),然后读取对应字段,比如errorContent.errorMsg。
  • 确保Spring Boot后端返回500响应时,正确设置Content-Type响应头:文本格式设为text/plain,JSON格式设为application/json,否则前端解析会失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:10:32