title: Firebase - Uncaught (in promise) TypeError: Cannot read property
body: <p>I've got 2 text boxes, one for username and the other for password.</p>
  
  <pre><code>&lt;input type="text" id="username"&gt;
  &lt;input type="text" id="password"&gt;
  &lt;input type="button" value="Login" onclick="authenticateUser()"&gt;
  </code></pre>
  
  <p>Here is the firebase code:</p>
  
  <pre><code>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);
    });
  }
  </code></pre>
  
  <p>It says:</p>
  
  <blockquote>
    <p>Uncaught (in promise) TypeError: Cannot read property 'email' of null</p>
  </blockquote>
  
  <p>The firebase code above works and fetches the email if the username is matched but what if the username doesn't exist, if it doesn't then it throws TypeError, how to catch that error?</p>
  
  <p>This unfortunately doesn't work:</p>
  
  <pre><code>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');
    });
  }
  </code></pre>
  
  <p>In case of email and password authentication, there is <code>catch</code></p>
  
  <pre><code>firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      // ...
  });
  </code></pre>
  
  <p>In Java, there is something like</p>
  
  <pre><code>catch(TypeError error) {
      //Do whatever you want to do
  }
  </code></pre>