繁体   English   中英

如何访问 AngularFire / TypeScript 中 FirebaseError 的“代码”属性?

[英]How do you access the "code" property of a FirebaseError in AngularFire / TypeScript?

FirebaseError 有一个“code”属性,但是如何在 promise 的 catch 方法中读取它呢? 以下内容引发了以下类型的 TypeScript 错误: Property 'code' does not exist on type 'Error'.

this.af.database
.object(`/some/path`)
.set(newObj)
.then(data => {
  console.log('success');
})
.catch(err => {
  // Property 'code' does not exist on type 'Error'.
  console.log(`code`, err.code);
});

要访问代码属性,您需要导入firebase并将错误提供给firebase.FirebaseError类型,如下所示:

import { AngularFire } from 'angularfire2';
import firebase from 'firebase';

...

constructor(
  private af: AngularFire
) {}

...

this.af.database
.object(`/some/path`)
.set(newObj)
.then(data => {
  console.log('success');
})
.catch( (err: firebase.FirebaseError) => {
  // Give your error the firebase.FirebaseError type and
  // you'll have access to all the FirebaseError properties
  console.log(`code`, err.code);
  console.log(`message`, err.message);
  console.log(`name`, err.name);
  console.log(`stack`, err.stack);
});

虽然Patrickmcd的解决方案可行。 这不是一个理想的解决方案。 您不应该依赖于导入firebase对象以在错误对象上具有正确的类型。 这违背了角度火力模块的要点。 它还会在您的应用程序中添加大量不必要的批量。 请在此处查看错误报告: https//github.com/angular/angularfire2/issues/666

计划在beta 7中修复

使用括号表示法和字符串文字我的解决方法不要求您导入Firebase库。

请参阅下面的示例

 this.af.auth.login({
      email: this.userEmail,
      password: this.userPassword
    }).catch(error => {
      // Returns the firebase Error Code documented here https://firebase.google.com/docs/reference/js/firebase.auth.Error
      console.log(error['code']);
      // Returns the fire base message associated with the Error Code
      console.log(error['message']);

      // Show failed login validation
      this.loginFailed = true;

    }); 

希望这可以帮助 !

另一种解决方案,您可以尝试从 '@firebase/util' 包中导入全局 FirebaseError 并使用类型保护进行检查,如下所示。

import { FirebaseError } from '@firebase/util'

try {
    // Some firebase functions
    await signInWithEmailAndPassword(auth, email, password)
} catch (error: unknown) {
   if (error instanceof FirebaseError) {
      console.error(error.code)
   }
}

如果您使用单独的 Firebase 模块,则每个模块都有一个错误类型。

import { FirestoreError } from 'firebase/firestore'

.catch( (err: FirestoreError) => {
  // Give your error the firebase.firestore.Error type and
  // you'll have access to all the Error properties
  console.log(`code`, err.code);
  console.log(`message`, err.message);
  console.log(`name`, err.name);
  console.log(`stack`, err.stack);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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