GoogleCloudPlatform/nodejs-getting-started

You can't throw from async functions without a catch block

Hoppingmad9 opened this issue · 2 comments

In firestore.js on line 77.

async function read(id) {
  const doc = await db.collection(collection).doc(id).get();

  if (!doc.exists) {
    throw new Error('No such document!');
  }
  return doc.data();
}

If the doc doesn't exist then it will result in a

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().

warning.

(Sorry for the back-and-forth labeling — this isn't about the Firestore API, per se, but rather about a .js file named firestore.js which includes sample code for thebookshelf sample application.)

bcoe commented

@Hoppingmad9 this structure is intentional, if someone is using this sample code, you would do so like this:

try {
  catch await read(id);
} catch (err) {
  // recover from error.
}