示例工程 20-network-storage-fetch

20-network-storage-fetch/01-fetch-status/main.js

javascript · 1.0 KB

运行:20 · fetch 与 4xx

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// main.js —— fetch 只在网络错误时 reject;4xx/5xx 仍然 resolve
export function classify(response) {
  const status = response.status;
  return {
    ok: response.ok,
    status,
    category:
      status >= 500 ? 'server-error' : status >= 400 ? 'client-error' : status >= 300 ? 'redirect' : 'success',
  };
}
 
export async function inspect(url, fetchImpl = fetch) {
  const response = await fetchImpl(url);
  const body = await response.text();
  return { ...classify(response), body: body.slice(0, 60) };
}
 
export async function run(log = console.log) {
  if (typeof fetch !== 'function') {
    throw new Error('本示例需要浏览器环境:请通过 index.html 打开');
  }
  const result = await inspect('./does-not-exist.json');
  log(`HTTP 状态:${result.status}`);
  log(`response.ok:${result.ok}`);
  log(`分类:${result.category}`);
  log(`响应体片段:${result.body}`);
  log('要点:4xx 不会让 await 抛错;必须检查 response.ok / status。');
  return result;
}