patrickmcd patrickmcd - 12 days ago 6
TypeScript Question

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

FirebaseError has a "code" property, but how do you read it in the catch method of a promise? The following throws a TypeScript error of:

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

Answer

To access the code property, you need to import firebase and give your error the firebase.FirebaseError type, like so:

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