firebase How do I listen for errors when accessing the database? Detecting errors when reading data in JavaScript


Example

A frequent reason why your read operation may not work is because your security rules reject the operation, for example because you're not authenticated (by default a database can only be accessed by an authenticated user).

You can see these security rule violations in the JavaScript console of your browser. But it's easy to overlook these. You can also handle them in your own code and make them more prominently visible, which is especially useful during development (since your JSON, rules and code change often).

To detect a failed read in JavaScript you must implement add a second callback to your on() clause:

ref.on('value', function(snapshot) {
    console.log(snapshot.key, snapshot.val());
}, function(error) {
    alert(error);
})

With this code in place it will be pretty hard to overlook a security error when reading data in JavaScript.