UnhandledPromiseRejectionWarning :异步回调函数中的错误处理

UnhandledPromiseRejectionWarning : error handling in an async callback function

我有一个异步回调函数,如果不满足某些条件,它会抛出错误。

但我收到以下错误

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

我的代码:

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
          );
        }
      });
  }

从回调函数中抛出错误的正确方法是什么?

在查看 .runTransaction() 的代码示例时,看起来它 return 是一个承诺,并且会从其回调中传播承诺拒绝(对于普通回调来说,这有点不同) ,但无论如何,看起来您只需要 return 来自 deleteItem() 方法的 firestoreDB.runTransaction() 的承诺,然后确保该方法的调用者正在使用 .catch()处理任何错误。

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
          );
        }
      });
  }

那么,无论你在哪里调用.deleteItem():

obj.deleteItem(...).catch(err => {
    // handle error here
});