【问题标题】:Firebase catch exceptionFirebase 捕获异常
【发布时间】:2017-08-18 03:58:39
【问题描述】:

如果我要保存到 firebase 的数据无效,我有以下代码会在控制台中向我抛出一些 firebase 异常。 我想捕获它并以受控的方式将其显示到屏幕上,而不是从控制台中查找。 我不知道为什么我的 .catch 没有捕获任何 firebase 异常?

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);
}

例外:Firebase.update 失败:第一个参数包含属性“codes.apple20170318.codes”中的无效键 ()。钥匙必须是 非空字符串,不能包含“.”、“#”、“$”、“/”、“[”或“]”

【问题讨论】:

  • real time DB 中提供有关您的数据模型的更多详细信息。
  • @ErnieKev 我也面临同样的问题。你知道如何克服它吗?我什至添加了外部全局 try-catch,但它仍然发生,因为我在回调中有一些“更新”调用。这是将 try-catch 无处不在的唯一方法吗?那么firebase的“catch”有什么用呢?

标签: javascript typescript firebase firebase-realtime-database


【解决方案1】:

这里没有什么可做的,但我最好的猜测是您传递给 saveCodesToFirebase() 的对象的键中包含点,就像错误消息中显示的那样:jobCodes.apple20170318.codes

如果您想保留此模型,则必须在执行 update() 操作之前清理该对象以替换其键(及其子键,递归)中的任何无效字符。

在捕获异常时,您必须使用 try/catch 块。在这种情况下,附加到 promise 的 .catch() 仅用于检测服务器返回的错误,但这里是 update() 方法本身同步抛出异常。

一种可能的方法是这样的:

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
}

【讨论】:

  • 我知道是这种情况并且很容易修复。但是,我的目标是能够通过一些 catch 语句以某种方式捕获此错误。
猜你喜欢
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 2021-04-24
  • 2023-02-21
  • 2021-04-12
  • 2016-10-17
  • 1970-01-01
相关资源
最近更新 更多