Skip to content
jshacks.dev
APIs

Normalize API errors into one shape

Normalize API errors into one shape by mapping HTTP failures, network errors, timeouts and unknown throws to a single object the UI can show.

2 min read
Summarize in AI

A fetch call can fail in four different ways, and each one throws something different. The interface should deal with one shape.

normalize.tsTypeScript
type AppError = { kind: 'http' | 'network' | 'timeout' | 'unknown'; message: string; status?: number };

class HttpError extends Error {
  status: number;
  constructor(status: number) {
    super(`HTTP ${status}`);
    this.status = status;
  }
}

function normalize(err: unknown): AppError {
  if (err instanceof HttpError) return { kind: 'http', status: err.status, message: err.message };
  if (err instanceof DOMException && err.name === 'TimeoutError') {
    return { kind: 'timeout', message: 'The request took too long' };
  }
  if (err instanceof TypeError) return { kind: 'network', message: 'Cannot reach the server' };
  return { kind: 'unknown', message: 'Something went wrong' };
}

console.log(normalize(new HttpError(404)));
console.log(normalize(new TypeError('fetch failed')));
console.log(normalize(new DOMException('', 'TimeoutError')));
console.log(normalize('oops'));
Text
{ kind: 'http', status: 404, message: 'HTTP 404' }
{ kind: 'network', message: 'Cannot reach the server' }
{ kind: 'timeout', message: 'The request took too long' }
{ kind: 'unknown', message: 'Something went wrong' }

The mapping rests on what each failure throws: your own error class for a bad status, a TypeError when fetch cannot reach the server, a DOMException named TimeoutError when an AbortSignal.timeout fires, and anything else for bugs.

The UI then switches on kind instead of testing error types. Write the user-facing text separately from the raw message so a server's wording never reaches the screen. The error classes are documented in fetch() exceptions on MDN.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read
Performance

Reduce JSON size by removing nulls

Drop null and undefined fields from an API payload with a JSON.stringify replacer, shrinking responses, and check clients treat a missing key like null.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.