简体   繁体   中英

Firebase database how to catch permission denied error

I hava a rule that allows reading in the database after one specific hour. If I try to read before the hour is over it throws an error: (permission_denied at /test: Client doesn't have permission to access the desired data) .

The problem is that I can not handle this error in my code because read operation does not return a promise.

Here is my code:

membersbet: Observable<any[]>;

  this.membersbet = this.afDB.list('/test').snapshotChanges().map((data) => {
    return data.map((c) => { 
      let memberinfo = [];   
      let subsArr: any[] = Object.entries(c.payload.val());
      subsArr.forEach(([key, value]) => {       
        memberinfo.push({"key": c.payload.key});                
      });
      return memberinfo;
    })
  })

  this.membersbet.subscribe(snapshots => {
    this.groupmembersArray = snapshots.reduce(function(a,b) {
      return a.concat(b);
    });
    console.log(this.groupmembersArray);      
  })      

Can anyone help me with this?

You'll need to .catch the error before you subscribe.

  this.membersbet.catch( e => {
    console.error(e);
    // just firing an empty array, do something smart or alternatively 
    //   empty() to just complete or never() to hang the subscription
    return of([]);
  }).subscribe(snapshots => {
    this.groupmembersArray = snapshots.reduce(function(a,b) {
      return a.concat(b);
    });
    console.log(this.groupmembersArray);      
  }) 

The error will terminate the subscription though; if you don't want that build retry logic with the .retry() or .retryWhen() operators; again before the subscription.

  this.membersbet
    // retry in 5 minutes, will keep retrying indefinitely 
    .retryWhen(e => e.delay(5 * 60 * 1000))
    .subscribe(snapshots => {
      this.groupmembersArray = snapshots.reduce(function(a,b) {
        return a.concat(b);
      });
      console.log(this.groupmembersArray);      
    }) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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