Handle errors across sequential requests in TypeScript
10 Several requests in a row, with every fault recorded
hardMake several requests one after another. Handle a failure from each, pass it up to the caller, and log every one. Adapted: a fake responder stands in for the network.
Stuck? Three hints, smallest first
- 1. Decide first whether one failure should stop the run or not. The two designs are very different.
- 2.
Promise.allSettledis the built-in for "try everything and tell me what happened". - 3. Keep the fake responder synchronous-but-async so top-level
awaitworks and the output stays predictable.
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 RequestError extends Error {
constructor(message: string, public readonly url: string) {
super(message);
this.name = 'RequestError';
}
}
const OK = new Set(['/a', '/b', '/d']);
async function request(url: string): Promise<string> {
// Resolved immediately, so the output order is predictable.
if (!OK.has(url)) throw new RequestError('request failed', url);
return `payload from ${url}`;
}
const log: string[] = [];
// Design one: stop at the first failure. Right when later steps depend on earlier ones.
async function sequentialStopOnFirst(urls: string[]): Promise<string[]> {
const out: string[] = [];
for (const url of urls) {
try {
out.push(await request(url));
} catch (err) {
if (err instanceof RequestError) log.push(`${err.name}: ${err.url}`);
throw err; // passed up to the caller
}
}
return out;
}
// Design two: try them all, report everything. Right when they are independent.
async function sequentialTryAll(urls: string[]): Promise<{ ok: string[]; failed: string[] }> {
const ok: string[] = [];
const failed: string[] = [];
for (const url of urls) {
try {
ok.push(await request(url));
} catch (err) {
if (err instanceof RequestError) {
log.push(`${err.name}: ${err.url}`);
failed.push(err.url);
} else throw err;
}
}
return { ok, failed };
}
const urls = ['/a', '/b', '/c', '/d'];
let stoppedAt = '';
try {
await sequentialStopOnFirst(urls);
} catch (err) {
stoppedAt = err instanceof RequestError ? err.url : '';
}
const all = await sequentialTryAll(urls);
console.log('stop-on-first gave up at', stoppedAt);
console.log('try-all succeeded for', all.ok.length, 'and failed for', all.failed);
for (const line of log) console.log('LOG', line);
test('stop-on-first stopped at the bad one', stoppedAt, '/c');
test('try-all got the three good ones', all.ok.length, 3);
test('try-all recorded the bad one', all.failed, ['/c']);
test('every failure was logged', log.length, 2);
test('the good payloads are intact', all.ok[0], 'payload from /a');
Output
The two designs are the actual content. Stop on the first failure when step three needs step two’s answer. Try everything and report when the calls are independent, because failing the whole batch over one bad URL loses three good results. In real code the second is often Promise.allSettled, which runs them at the same time as well.