简体   繁体   中英

how do I catch firebase search error?

I have a function that takes user's input and search through firebase database. What I want to do is catch the any error most especially when their is no match for the user input I want to display as something like "No match was found for the number entered".

this is the function I'm using

function searchNSN(data){

    var container = document.getElementById('searchresult'); 
    container.innerHTML = '';
    var FindNSN = document.getElementById('searchinput').value;

    firebase.auth().onAuthStateChanged((user) => {
        if (user) {
            var BusinessesId = firebase.auth().currentUser.uid;
            return database.ref('/Businesses/' + BusinessesId + '/Inventory/' + FindNSN).once('value').then(function(snapshot) {
                var Results = snapshot.val();
                var Productkey = Object.keys(snapshot.val())[0];
                var ResultCard = `
                  <h1 class="searchtitle first">${Results.ProductName}</h1>
                  <p class="searchtext">${Results.ProductDescription}<span class="class">${Results.NSN}</span></p>
                  <p class="showproductdetail" onclick="SHOWSEARCHDETAIL();"><a href> Show Product Details </a href></p>

                    `
                    container.innerHTML += ResultCard;

            });
        }
    })
}

I know the console logs the error but how do I implement catching the error and reporting it to the user?

If the database location/reference does not contain any data, it will still trigger a value event but with an empty DataSnapshot (ie snapshot.val() is null ). You may check if snapshot.val() === null , and if it does, let the user know that there are no results.

Reference , the value event section.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM