javascript - 抛出异常破坏 promise 链

标签 javascript node.js firebase google-cloud-functions

目前,如果 asyncFunction1() 的 Promise 回调中捕获到错误,应用将正确抛出“问题 A”异常。但是,这是通过 promise 链传递的,应用程序最终会看到“问题 B”,这意味着应用程序向用户显示错误的错误。

我实际上需要中止执行并打破链条,同时抛出相关错误。我怎样才能做到这一点?

可以在此处找到 HttpsError 类信息:https://firebase.google.com/docs/reference/functions/functions.https.HttpsError

它明确提到:

Make sure to throw this exception at the top level of your function and not from within a callback, as that will not necessarily terminate the function with this exception.

我似乎陷入了这个陷阱,但不知道如何解决它。如果有人可以帮助我重构代码,以便我能够有效地捕获并正确处理这些错误,我将不胜感激。

exports.charge = functions.https.onCall(data => {
  asyncFunction1()
    .then(() => {
      asyncFunction2();
    })
    .catch((err) => {
      throw new functions.https.HttpsError(
        'not-found',
        'Problem A'
      );
    })
    .then(() => {
      asyncFunction3();
    })
    .catch((err) => {
      throw new functions.https.HttpsError(
        'not-found',
        'Problem B'
      );
    })
});

最佳答案

有多种不同的方法可以解决这个问题:

  1. 您可以让每个异步函数在拒绝时设置适当的错误,这样您就不必在自己的 .catch() 中手动添加正确的错误。

  2. 您可以在最后一个 .catch() 中进行测试,看看是否已经设置了适当的错误,如果是,则重新抛出它,而不是用另一个错误覆盖它。

  3. 您可以将最后一个 .catch() 直接放在 asyncFunction3() 调用上,而不是像这样放在整个链上,这样您就只定位该函数拒绝该错误代码:

修改后的代码:

exports.charge = functions.https.onCall(data => {
    return asyncFunction1().then(() => {
        return asyncFunction2();
    }).catch((err) => {
        // set appropriate error for rejection in either of the first two async functions
        throw new functions.https.HttpsError('not-found', 'Problem A');
    }).then(() => {
        return asyncFunction3().catch((err) => {
            // set appropriate error for rejection in asyncFunction3
            throw new functions.https.HttpsError('not-found', 'Problem B');
        });
    });      
});

注意:我还添加了几个 return 语句,以确保 Promise 链接到链中并从导出函数返回。而且,我压缩了逻辑以使其更易于阅读。


这也可能是 async/await 的情况(尽管我不完全确定 functions.https.onCall() 是否允许这样做):

exports.charge = functions.https.onCall(async (data) => {
    try {
        await asyncFunction1()
        await asyncFunction2();
    } catch(e) {
        throw new functions.https.HttpsError('not-found', 'Problem A');
    }
    try {
        await asyncFunction3();
    } catch(e) {
        throw new functions.https.HttpsError('not-found', 'Problem B');
    }
});

关于javascript - 抛出异常破坏 promise 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53090619/

相关文章:

node.js - Node 未从 Gruntfile 中找到依赖项

java - 如何跳过唯一的用户 ID 并访问回收者 View 的子值

swift - Firestore : create subcollection from iOS SDK

Firebase 身份验证 : Is it possible to be logged in on two devices at the same time?

javascript - "has"表达式中的 "this.has"来自哪里?

javascript - JQuery UI 自动完成 - 无法加载对象

javascript - 使用 ng-bind-html 时 Angular 选项卡会中断

javascript - Vb.net fileupload预览图像使用javascript

node.js - 是否可以在编辑器中而不是在 Web 浏览器中运行 React.js 调试器

javascript - 快照参数/服务在 Angular 2 中返回 NaN