【问题标题】:Firebase admin sdk calling the wrong catchFirebase admin sdk 调用错误的捕获
【发布时间】:2021-12-21 03:30:31
【问题描述】:

我正在尝试使用firebase-admin 添加新用户,然后将新文档保存在自定义集合中。

示例代码如下:

admin.auth().createUser(user)

    .then((record) => {

       user.uid = record.uid;

       userCollection.doc(record.uid).set({...user})

           .then(writeResult => {
               resolve();
           })
           .catch(reason => {
               reject(reason)
           });
    })
    .catch((err) => {
        reject(err);
    });

问题是,如果userCollection.doc(record.uid).set({...user}) 失败,我希望调用嵌套的catch(以reason 作为参数)。相反,总是调用外部的(以err 作为参数)。

SDK 有问题还是我做错了什么?

谢谢

【问题讨论】:

    标签: javascript node.js firebase google-cloud-firestore firebase-admin


    【解决方案1】:

    这是因为你没有返回由userCollection.doc(record.uid).set() 返回的承诺,因此你没有返回由随后的then()catch() 方法返回的承诺。换句话说,您不会返回promises chain

    但是,实际上,您应该将 Promise 链接如下,并避免使用 then()/catch() 金字塔。

      admin
        .auth().createUser(user)
        .then((record) => {
          user.uid = record.uid;
    
          return userCollection
            .doc(record.uid)
            .set({ ...user })
        })
        .catch((err) => {
    
          // Here you catch the potential errors of 
          // the createUser() AND set() methods
    
          console.log(JSON.stringify(err));
    
        });
    

    更多详情hereherehere

    【讨论】:

    • 感谢您的帮助。我将阅读有关链接的更多信息,但我有一个问题,如果调用了 catch 方法,我如何理解你的代码出了什么问题?
    • 查看更新。通常的方法是分析err 对象。在这里,我刚刚使用console.log(JSON.stringify(err)); 记录了它,但您可以获取此对象的messagecode 属性并采取相应措施。
    • 例如createUser()方法返回的错误码列在here
    • 好的,显然这是一个解决方案,但我认为对于具有越来越多嵌套承诺的更大项目可能会出现问题。单独管理所有捕获不是更好吗?
    • 最佳实践是避免使用then()/catch() 金字塔。更多解释here。换句话说,使用 Promises 我们可以避免回调金字塔,这可能会成为一场噩梦,尤其是大型项目,所以你可能不想用 Promises 构建另一个金字塔 ;-)
    猜你喜欢
    • 1970-01-01
    • 2018-05-17
    • 2019-07-09
    • 2017-12-13
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多