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

pat*_*mcd 3 firebase typescript angularfire angular

FirebaseError有一个"代码"属性,但是如何在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);
});
Run Code Online (Sandbox Code Playgroud)

Juk*_*Juk 14

另一种解决方案,您可以尝试从“@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)
   }
}
Run Code Online (Sandbox Code Playgroud)


pat*_*mcd 6

要访问代码属性,您需要导入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);
});
Run Code Online (Sandbox Code Playgroud)