如何在 AngularFire / TypeScript 中访问 FirebaseError 的"code"属性?



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

要访问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对象来获得Error object上的正确类型。这就违背了Angular Fire模块的宗旨。它还会在应用程序中添加大量不必要的块。请在这里查看bug报告: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模块,每个模块都有一个错误类型。

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

最新更新