【问题标题】:Firebase - Uncaught (in promise) TypeError: Cannot read propertyFirebase - 未捕获(承诺)类型错误:无法读取属性
【发布时间】:2016-07-28 14:50:08
【问题描述】:

我有 2 个文本框,一个用于用户名,另一个用于密码。

<input type="text" id="username">
<input type="text" id="password">
<input type="button" value="Login" onclick="authenticateUser()">

这是firebase代码:

function authenticateUser() {
  var username = document.getElementById('username').value;
  var password = document.getElementById('password').value;

  database.ref('users/'+username).once('value').then(function(snapshot) {
    var email = snapshot.val().email;
    console.log(email);
  });
}

上面写着:

Uncaught (in promise) TypeError: Cannot read property 'email' of null

如果用户名匹配,上面的 firebase 代码可以工作并获取电子邮件,但如果用户名不存在怎么办,如果不存在则抛出 TypeError,如何捕获该错误?

不幸的是,这不起作用:

function authenticateUser() {
  var username = document.getElementById('username').value;
  var password = document.getElementById('password').value;

  database.ref('users/'+username).once('value').then(function(snapshot) {
    var email = snapshot.val().email;
    console.log(email);
  }, function(error) {
    console.log('Invalid Username');
  });
}

在邮箱和密码认证的情况下,有catch

firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // ...
});

在Java中,有类似的东西

catch(TypeError error) {
    //Do whatever you want to do
}

【问题讨论】:

    标签: javascript firebase firebase-realtime-database firebase-authentication


    【解决方案1】:
    try {
       snapshot.val().email
    } catch(e) {
        if (e instanceof TypeError) {
        ....
        }
    }
    

    更多https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

    但您似乎也可以通过空检查(这通常比触发可避免的异常更适合“流控制”)

    var user = snapshot.val();
    if (user == null) { /* error */}
    

    【讨论】:

      猜你喜欢
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 2018-10-29
      • 2020-12-15
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多