fetch api 默认不因 http 状态码异常抛错,仅网络失败时 reject;需手动检查 response.ok 或 status,并处理 json 解析失败等非 http 异常。

Fetch API 默认不会因 HTTP 状态码(如 404、500)抛出错误,它只在网络失败(如断网、DNS 失败)时 reject。所以处理状态码异常必须手动检查 response.ok 或 response.status。
判断响应是否成功(推荐用 response.ok)
response.ok 是布尔值,等价于 response.status >= 200 && response.status 。这是最简洁、语义最清晰的方式。
- ✅ 正确做法:调用
response.json()前先检查if (!response.ok) - ❌ 错误做法:直接
await response.json(),忽略 4xx/5xx 状态码
示例:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
fetch('/api/user/123')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(err => console.error('请求失败:', err.message));
按具体状态码做差异化处理
有时你需要对不同错误码执行不同逻辑,比如 401 跳登录页、404 显示提示、500 触发重试。
- 用
response.status获取精确状态码 - 配合
response.statusText可读性更好(如 "Not Found") - 注意:某些环境(如 CORS 请求)可能无法读取
statusText,建议以status为主
示例:
fetch('/api/data')
.then(async response => {
switch (response.status) {
case 401:
window.location.href = '/login';
break;
case 404:
alert('资源不存在');
break;
case 500:
throw new Error('服务器内部错误,请稍后重试');
default:
if (!response.ok) throw new Error(`请求失败: ${response.status}`);
return response.json();
}
})
.catch(err => console.error(err));
统一封装错误处理逻辑
避免每个请求都重复写状态码判断,可封装一个工具函数:
- 自动抛出带状态信息的错误
- 支持自定义错误映射(如把 429 映射为 "请求太频繁")
- 返回标准化的错误对象,方便上层统一捕获
示例:
async function safeFetch(url, options = {}) {
const res = await fetch(url, options);
if (!res.ok) {
const error = new Error(res.statusText || `HTTP ${res.status}`);
error.status = res.status;
error.response = res;
throw error;
}
return res;
}
// 使用
safeFetch('/api/profile')
.then(r => r.json())
.catch(err => {
if (err.status === 401) handleAuthError();
else if (err.status === 429) showRateLimitTip();
});
注意:JSON 解析失败也是常见“异常”
即使状态码是 200,响应体不是合法 JSON 也会导致 .json() 抛错。这不属于 HTTP 异常,但实际开发中极易被忽略。
- 在
response.json()后加catch捕获解析错误 - 或用
response.text()先获取原始文本,再手动JSON.parse()并 try-catch
示例:
fetch('/api/data')
.then(res => {
if (!res.ok) throw new Error(`${res.status}`);
return res.json().catch(() => {
throw new Error('响应内容不是有效 JSON');
});
})
.then(data => console.log(data))
.catch(err => console.error(err.message));
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










