Custom ApiError for failed requests in TypeScript
6 An ApiError for a failed request
fairFetch data from an API and use a custom error class for request failures. Adapted: no network here, so a fake responder stands in and fails in the same shapes a real one does.
Stuck? Three hints, smallest first
- 1. Carry the HTTP status on the error, since the caller usually branches on it.
- 2. A 404 and a 500 deserve different handling: one is the caller’s fault, one is not.
- 3.
fetchonly rejects on a network failure, not on a 404. You must checkresponse.okyourself.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
class ApiError extends Error {
constructor(
message: string,
public readonly status: number,
public readonly url: string,
) {
super(message);
this.name = 'ApiError';
}
get isClientFault(): boolean { return this.status >= 400 && this.status < 500; }
get isServerFault(): boolean { return this.status >= 500; }
}
// The real version would be:
// const response = await fetch(url);
// if (!response.ok) throw new ApiError(response.statusText, response.status, url);
// return await response.json();
//
// Note the trap: fetch does NOT reject on a 404. Checking response.ok is on you.
type Payload = { plate: string; seatsLeft: number };
const ROUTES = new Map<string, { status: number; body?: Payload }>([
['/bus/LAG-441-XA', { status: 200, body: { plate: 'LAG-441-XA', seatsLeft: 9 } }],
['/bus/UNKNOWN', { status: 404 }],
['/bus/BROKEN', { status: 500 }],
]);
function request(url: string): Payload {
const route = ROUTES.get(url);
if (route === undefined) throw new ApiError('no route', 404, url);
if (route.status !== 200 || route.body === undefined) {
throw new ApiError(`request failed with ${route.status}`, route.status, url);
}
return route.body;
}
function load(url: string): string {
try {
const data = request(url);
return `${data.plate}: ${data.seatsLeft} seats left`;
} catch (err) {
if (err instanceof ApiError) {
if (err.isClientFault) return `not found: ${err.url}`;
if (err.isServerFault) return `server trouble on ${err.url}, try again shortly`;
}
throw err;
}
}
console.log(load('/bus/LAG-441-XA'));
console.log(load('/bus/UNKNOWN'));
console.log(load('/bus/BROKEN'));
test('a good response', load('/bus/LAG-441-XA'), 'LAG-441-XA: 9 seats left');
test('a 404 is the caller\'s problem', load('/bus/UNKNOWN'), 'not found: /bus/UNKNOWN');
test('a 500 is not', load('/bus/BROKEN'), 'server trouble on /bus/BROKEN, try again shortly');
test('the status is on the error', (() => { try { request('/bus/BROKEN'); return 0; } catch (e) { return e instanceof ApiError ? e.status : 0; } })(), 500);
Output
Adapted: the usual version calls a live API. The lesson that matters is unchanged and is written in the comment: fetch resolves happily on a 404, so a request that "worked" can still have failed. You have to check response.ok and throw yourself. The isClientFault and isServerFault getters put the retry decision on the error, where it belongs.