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.
A fetch call can fail in four different ways, and each one throws something different. The interface should deal with one shape.
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'));{ 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.