0

I am converting the use of Firebase Storage to use the Angularfire2 library (currently v5.0.0-rc.5-next) which means I am now using observables rather than promises.

How can I catch error such as storage/object-not-found and react accordingly?

This is currently my code but I cannot add a catch to it as some examples I found.

const avatarRef =  this.afStorage.ref('${userId}/avatar/${this.avatarThumbnail}${user.avatar}');

avatarRef.getDownloadURL()
    .take(1)
    .subscribe((avatarUrl) => {
        resolve(avatarUrl);
    });
Xerri
  • 4,916
  • 6
  • 45
  • 54

2 Answers2

3

At its most basic, observers take an error callback to receive any unhandled errors in an observable stream. getDownloadURL() returns Observable that is why you need to subscribe. If you get an error (file not found or other) you will invoke code from error callback only.

avatarRef.getDownloadURL()
.take(1)
.subscribe((avatarUrl) => {
    // Do something with avatarUrl here
   console.log(avatarUrl);
}, (error) => {
   // Handle error here
   // Show popup with errors or just console.error
   console.error(error);
});

Also I suggest you to read articles about error handling using RxJS and difference between Observable and Promise: link1, link2

0

The following solution work for me

startUpload(file) {

    // The storage path
    const path = `image${new Date().getTime()}.jpg`;

    // Reference to storage bucket
    const ref = this.storage.ref(path);
    let image = 'data:image/jpeg;base64,' + file;
    // The main task
    return new Promise((resolve, reject) => {
      const upload = ref.putString(image, 'data_url');
      const sub = upload.snapshotChanges().pipe(
        finalize(async () => {
          try {
            const photoURL = await ref.getDownloadURL().toPromise();
            this.message.senderUid = this.currentUser.uid;
            this.message.receiverUid = this.selectedUser.uid;
            this.message.text = this.inputText && this.inputText !== '' ? this.inputText : 'File';
            this.message.senderName = this.currentUser.name;
            this.message.chatId = this.chatId;
            this.message.file = photoURL;
            this.firebaseService.insertMessage(this.message)
              .then(() => {
                this.inputText = '';
                this.message.file = null;
                this.scrollToBottomOnInit();
              });

            resolve({photoURL})
          } catch (err) {
            this.inputText = '';
            this.message.file = null;
            reject(err)
          }
          sub.unsubscribe()
        })
      ).subscribe((data) => {
        console.log('storage: ', data)
      })
    })
  }

Source: https://github.com/angular/angularfire/issues/1736#issuecomment-515798352

amit ghosh
  • 81
  • 7