Skip to content
Advertisement

UnhandledPromiseRejectionWarning : error handling in an async callback function

I have an async callback function, which throws an error if some condition isn’t met.

but I get the below error

(node:77284) UnhandledPromiseRejectionWarning: Error: Not Found

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().

My Code :

async deleteItem(id: string): Promise<void> {
    const ref = firestoreDB.collection("items").doc(id);

    firestoreDB
      .runTransaction(async (transaction: FirebaseFirestore.Transaction) => {
        let doc = await transaction.get(ref);
        if (doc.exists) {
          transaction.delete(ref);
        } else {
          throw new NotFoundException();
        }
      })
      .catch((err) => {
        if (err instanceof NotFoundException) {
          throw err;
        } else {
          throw new HttpException(
            "Something went wrong",
            HttpStatus.INTERNAL_SERVER_ERROR
          );
        }
      });
  }

What is the proper way to throw an error from the callback function?

Advertisement

Answer

In looking at code examples for .runTransaction(), it looks like it returns a promise and will propagate a promise rejections from its callback (that’s a bit of a different interface for a plain callback), but in any case, it looks like you just need to return the promise from firestoreDB.runTransaction() from your deleteItem() method and then make sure the caller of that method is using .catch() to handler any errors.

async deleteItem(id: string): Promise<void> {
    const ref = firestoreDB.collection("items").doc(id);

    // add return here
    return firestoreDB
      .runTransaction(async (transaction: FirebaseFirestore.Transaction) => {
        let doc = await transaction.get(ref);
        if (doc.exists) {
          transaction.delete(ref);
        } else {
          throw new NotFoundException();
        }
      })
      .catch((err) => {
        if (err instanceof NotFoundException) {
          throw err;
        } else {
          throw new HttpException(
            "Something went wrong",
            HttpStatus.INTERNAL_SERVER_ERROR
          );
        }
      });
  }

Then, wherever you call .deleteItem():

obj.deleteItem(...).catch(err => {
    // handle error here
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement