Firebase catch exception

14,637

There's not much to go on here but my best guess is that the object you're passing to saveCodesToFirebase() has keys that contain dots in them, like the one shown in the error message: jobCodes.apple20170318.codes.

If you want to keep this model you will have to sanitize that object to replace any invalid characters in its keys (and its children keys, recursively) before doing the update() operation.

When it comes to catching the exception, you'll have to use a try/catch block. The .catch() attached to the promise in this case is only useful to detect errors returned by the server, but here it's the update() method itself the one synchronously throwing the exception.

One possible approach would be like this:

try {
  this.databaseService.saveCodesToFirebase(jsonFromCsv)
    .then(result => {
      this.alertService.alertPopup('Success', 'Code Updated')
    })
    .catch(error => {
      this.errorMessage = 'Error - ' + error.message
    })
} catch (error) {
  this.errorMessage = 'Error - ' + error.message
}
Share:
14,637
ErnieKev
Author by

ErnieKev

Updated on June 08, 2022

Comments

  • ErnieKev
    ErnieKev almost 2 years

    I have the following code that is throwing me some firebase exception in the console if the data that I want to save to firebase is invalid. I want to catch it and display it to the screen in a controlled manner rather than finding out from console. I dont know why my .catch is not catching any of the firebase exceptions?

    this.databaseService.saveCodesToFirebase(jsonFromCsv)
      .then(result => {
        this.alertService.alertPopup('Success', 'Code Updated')
      })
      .catch(error => {
        this.errorMessage = 'Error - ' + error.message
      })
    
    
    saveCodesToFirebase(myObj: Object) {
        let ref = firebase.database().ref();
    
        let path = this.userService.getCurrentUser().companyId + '/codes/'
        let lastUpdatedPath = this.userService.getCurrentUser().companyId + '/lastUpdated/';
    
        var updates = {}
    
        updates[path] = jobObject;
        updates[lastUpdatedPath] = Math.round(new Date().getTime() / 1000);
    
        return ref.child('codes').update(updates);
    }
    

    EXCEPTION: Firebase.update failed: First argument contains an invalid key () in property 'codes.apple20170318.codes'. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"

    screen shot