#42 · Async

Find the bug · #42 · Async Hard JavaScript

Failed saves are never retried

Drafts that fail to save should go to a retry queue, but the queue is always empty.

On this page

The report

Bug report

When saving a draft fails (on a bad network, say), the draft should go into a retry queue. In production the queue is always empty, and users lose drafts whenever the network blips.

The code

Read it first: what should it do? Then click the line where you think the bug is.

JavaScriptClick the line you think is wrong
// Saves a draft; if saving fails, the draft is queued to retry later.
async function saveDraft(draft, api, retryQueue) {
  try {
    return api.save(draft);
  } catch (err) {
    retryQueue.push(draft);
    return 'queued';
  }
}

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
const api = { save: async () => { throw new Error('network down'); } };
const queue = [];
try {
  console.log(await saveDraft({ id: 1 }, api, queue));
} catch (e) {
  console.log('error: ' + e.message);
}
console.log('queued drafts: ' + queue.length);

It prints

error: network down
queued drafts: 0

It should print

queued
queued drafts: 1
Show the answer: the bug, the fix, and how you’d find it

The bug (line 4)

Line 4 returns the promise from api.save without awaiting it. The try block is done the moment the promise is handed back, so when it rejects a little later, the catch is long gone and the error goes straight to the caller. return await keeps the rejection inside the try.

The fix

1// Saves a draft; if saving fails, the draft is queued to retry later.2async function saveDraft(draft, api, retryQueue) {3  try {4    return api.save(draft);4    return await api.save(draft);5  } catch (err) {6    retryQueue.push(draft);7    return 'queued';

How you’d find it

  1. Reproduce with a save that always fails: the caller gets the error, and the queue stays empty.
  2. So the catch never ran, even though the error came from inside the try. Put a log in the catch to be sure: silent.
  3. The try only catches errors thrown while it’s running. A promise that rejects after being returned is outside it.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

const queue = [];
const result = await saveDraft({ id: 2 }, { save: async () => { throw new Error('x'); } }, queue);
assert.equal(result, 'queued');
assert.equal(queue.length, 1);
assert.equal(await saveDraft({ id: 3 }, { save: async () => 'saved' }, []), 'saved');

Where else this bites

  • try { promise.then(...) } catching nothing for the same reason.
  • Python: returning a coroutine from inside try without awaiting it.
Your progress stays on this device.