← Back to JavaScript, page 4

javascript-0076 · Medium mid

How does the fetch API handle errors, and how do you send JSON, read responses safely, and set a timeout?

fetch rejects only for network failures, not for HTTP error statuses, so code must check response.ok. The body can be read once with json() or text(), and a bad body throws a separate error. JSON requests need a Content-Type header and a stringified body, and AbortSignal.timeout adds a time limit that rejects with a TimeoutError.

Full answer

fetch(url, options) returns a promise for a Response. The promise rejects when no response arrives, for example when the network is down, DNS fails, or the request is aborted. A response with status 404 or 500 is still a successful fetch from the promise's point of view. Code must check response.ok (true for statuses 200 to 299) or response.status, and throw its own error otherwise.

The body is a stream that can be read once: response.json(), response.text(), response.blob(), or response.arrayBuffer(). Calling two of them on the same response fails, since bodyUsed becomes true. Use response.clone() before reading when two reads are needed. json() can throw if the body is not valid JSON, so an error response with an HTML body needs care.

To send JSON, set method: 'POST', add the header Content-Type: application/json, and pass body: JSON.stringify(data). Without the header, many servers do not parse the body. Cookies are not sent to other origins by default; the credentials option controls that.

For timeouts and cancellation, pass signal. AbortSignal.timeout(ms) gives a signal that aborts itself and rejects with a TimeoutError. Combine it with a user cancel signal using AbortSignal.any.

A small wrapper that checks ok, parses JSON, and adds status information to errors keeps application code short. Retrying should be limited to safe, repeatable requests.

The code below starts a local test server, so it runs without internet access. In a browser, the same fetch calls work against a real URL, subject to CORS.

javascript
const http = require('node:http');

const server = http.createServer((req, res) => {
  if (req.url === '/ok') {
    res.setHeader('Content-Type', 'application/json');
    return res.end(JSON.stringify({ message: 'hello' }));
  }
  if (req.url === '/missing') {
    res.statusCode = 404;
    res.setHeader('Content-Type', 'text/html');
    return res.end('<h1>Not found</h1>');
  }
  if (req.url === '/echo' && req.method === 'POST') {
    let body = '';
    req.on('data', (chunk) => (body += chunk));
    return req.on('end', () => {
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify({ received: JSON.parse(body), type: req.headers['content-type'] }));
    });
  }
  if (req.url === '/slow') return setTimeout(() => res.end('late'), 300);
  res.statusCode = 500;
  res.end('unexpected');
});

async function getJson(url, options) {
  const response = await fetch(url, options);
  if (!response.ok) {
    const error = new Error(`HTTP ${response.status}`);
    error.status = response.status;
    throw error;
  }
  return response.json();
}

server.listen(0, '127.0.0.1', async () => {
  const base = `http://127.0.0.1:${server.address().port}`;

  console.log(await getJson(`${base}/ok`));

  const notFound = await fetch(`${base}/missing`);
  console.log('404 did not reject:', notFound.ok, notFound.status);
  try {
    await notFound.json();
  } catch (error) {
    console.log('HTML body parsed as JSON:', error.name);
  }
  try {
    await getJson(`${base}/missing`);
  } catch (error) {
    console.log('wrapper error:', error.message, error.status);
  }

  console.log(await getJson(`${base}/echo`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'Asha' }),
  }));

  const once = await fetch(`${base}/ok`);
  const copy = once.clone();
  await once.json();
  console.log('bodyUsed:', once.bodyUsed, 'clone still readable:', (await copy.json()).message);
  try {
    await once.json();
  } catch (error) {
    console.log('second read:', error.name);
  }

  try {
    await fetch(`${base}/slow`, { signal: AbortSignal.timeout(50) });
  } catch (error) {
    console.log('timeout:', error.name);
  }

  const closed = http.createServer().listen(0, '127.0.0.1');
  await new Promise((resolve) => closed.once('listening', resolve));
  const closedPort = closed.address().port;
  await new Promise((resolve) => closed.close(resolve));
  try {
    await fetch(`http://127.0.0.1:${closedPort}/`);
  } catch (error) {
    console.log('network failure:', error.name);
  }

  server.close();
  server.closeAllConnections();
});

Run with Node.js v24.22.1 as js-76.js; two runs gave identical output. Output: { message: 'hello' } 404 did not reject: false 404 HTML body parsed as JSON: SyntaxError wrapper error: HTTP 404 404 { received: { name: 'Asha' }, type: 'application/json' } bodyUsed: true clone still readable: hello second read: TypeError timeout: TimeoutError network failure: TypeError

Key points

  • fetch rejects on network failure or abort, not on 404 or 500.
  • Check response.ok and throw for error statuses.
  • The body can be read once; use clone() for two reads.
  • JSON requests need a Content-Type header and a stringified body.
  • AbortSignal.timeout adds a timeout; the rejection is a TimeoutError.

Common mistakes

  • Assuming fetch rejects on 404 or 500 and skipping the response.ok check.
  • Forgetting the Content-Type header when sending JSON.
  • Reading the body twice without cloning.
  • Having no timeout, so a stalled request waits indefinitely.

Follow-ups

  • How would you upload a file or form data with fetch?
  • How do credentials: 'include' and cookies interact with CORS?
  • How would you retry only safe requests?

Tips

  • Lead with "fetch only rejects on network failure"; it is the question's main trap.
  • Show a small wrapper that checks ok and throws a typed error.
  • Mention AbortSignal.timeout for timeouts; it replaces manual timer code.