【问题标题】:Getting 'Uncaught' after catching error in firebase.auth() with async在使用异步的 firebase.auth() 中捕获错误后得到“未捕获”
【发布时间】:2019-01-20 00:11:28
【问题描述】:
async login({ commit }, { email, password }) {
  let result
  try {
    result = await firebase.auth().signInWithEmailAndPassword(email, password)
    commit('setUser', result.user)
  } catch (err) {
    commit('setError', err)
  }
}

这是 Vuex 中的一个动作。当它运行时,我希望 commit('seteError', err) 成为从 catch (err) 返回的错误的有效错误处理程序。相反,我得到一个“未捕获”异常并停止执行。

如果有人设法将asyncfirebase.auth() 结合使用,我们将不胜感激

【问题讨论】:

  • 请将您的异常/错误作为代码示例 ({}) 包含在您的问题中。异常真的只是'Uncaught'吗?
  • 确实,这就是全部信息:Uncaught K {ob: Observer}。这里K是err返回的错误对象,我将其传递给commit
  • 我也有同样的问题。 Uncaught L {code: "auth/invalid-email", message: "The email address is badly formatted."}。塞萨尔,你找到答案了吗?
  • 我遇到了同样的问题。 Uncaught Bg {code: "auth/account-exists-with-different-credential", message: "An account already exists with the same email addr…ng a provider associated with this email address.", email: "XXXXXX", credential: Vf}。我发现错误并可以记录它,但它仍然显示为未捕获...

标签: javascript firebase async-await firebase-authentication


【解决方案1】:

这就是我设法在 Vuex 中使用异步处理 firebase 身份验证的方法。我需要使用onAuthStateChanged

async login({ commit, dispatch }, { email, password }) {
  try {
    await firebase.auth().signInWithEmailAndPassword(email, password)

    await dispatch('session')
  } catch (err) {
    commit('setError', err)
  }
}

“会话”调度的作用是:

async session({ commit }) {
  let user
  try {
    user = await userInSession()
    commit('setUser', user)
  } catch (err) {
    console.error(err)
    commit('setUser', {})
  }
}

而userInSession函数使用onAuthStateChanged

const userInSession =  function () {
  return new Promise((resolve, reject) => {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        resolve(user.uid)
      } else {
        reject(Error('No user authenticated'))
      }
    })
  })
}

【讨论】:

    【解决方案2】:

    我今天遇到了同样的问题 - 这似乎是由于 firebase auth 使用的 Closure promise 库的实现。 firebase-js-sdk 项目here 中有一个已关闭的问题,其中包含一些详细信息。最终,这种植入发生的事情是设置超时,引发超出try/catch 范围的异常:

    为避免这种情况,需要通过在返回的 Promise 上调用 .catch() 来处理异常,例如:

    firebase.auth().signInWithEmailAndPassword(email, password)
      .catch((ex) => { /* handle exception */ });
    

    由于我已将所有 firebase 逻辑打包并集中,我最终将 firebase Promise 打包到我自己的一个中:

    export async function signIn(email, password) {
      return new Promise((resolve, reject) => {
        firebase.auth().signInWithEmailAndPassword(email, password)
          .then((userCreds) => resolve(userCreds))
          .catch((reason) => reject(reason));
      });
    }
    

    然后可以使用 async await 调用包装函数:

    try {
      const result = await signIn(email, password)
      // Do what you need to with the result
    } catch (ex) {
      // Handle any exceptions
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-27
      • 2018-04-20
      • 2020-09-12
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      相关资源
      最近更新 更多