简体   繁体   中英

How do I catch an error from Observable in Firestore?

I have the following method in Angular (9) which attempts to find a document in firestore based on an id. However, if the document does not exist in firestore, I want to have a custom message for the user. I tried 3 different ways to catch errors, summarized in this code:

  joinGame(name, gameID): void {
    this.changeName(name);
    if (this.nameValid(name)) {
      sessionStorage.setItem('gameID', gameID);
      this.ws.joinGame(gameID, name);
      try {
        const gameDoc = this.afs.doc('games/' + gameID);
        const game = gameDoc.valueChanges();
        game.pipe(catchError => of([])).subscribe(data => {
          //@ts-ignore
          this.localGame = data.game;
        }, err => console.log(err));
      } catch (err) {
        console.log(err);
      }
    } else {
      this.nameError = true;
    }
  }

1- try-catch

2- catch after subscribe

3- catchError (I don't actually know what this is but I thought to try it anyway).

Anyway, none of these seemed to console.log what I wanted or handle the error gracefully. The console just gave the default error no matter what I logged. I know I can also just try not even let the user enter an invalid ID with a check before subscribing, but I was wondering if there is a better solution for doing this more automatically? Thank you!

I think there is a better way to do that instead of relying on catching an error, that is because after you use .doc('someId').get() you can already check if the resulting document exists or not, without throwing errors. So I would change the code you have to the following:

joinGame(name, gameID): void {
    this.changeName(name);
    if (this.nameValid(name)) {
        sessionStorage.setItem('gameID', gameID);
        this.ws.joinGame(gameID, name);
        try {
            const gameDoc = this.afs.doc('games/' + gameID).get().then(docSnapshot => {
                if(docSnapshot.exists){
                    const game = gameDoc.valueChanges();
                    game.subscribe(data => {
                        //@ts-ignore
                        this.localGame = data.game;
                    }
                }else{
                    console.log("The document does not exist in the Firestore");
                }
            });
        } catch (err) {
            console.log(err);
        }
    } else {
        this.nameError = true;
    }
}

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