1
votes

I've been trying to figure out how to handle Firebase errors for the firestore using async/await. I want to show an error message, if a doc doesn't exist but I'm a little confused about how I would do that with async/await.

getResult.js

If I purposely give a fake document ID, the catch function automatically takes over and I can no longer access result.exists which is what I need in this case. Is there a way I can easily check what type of error it is when I catch it, so I can return an appropriate message?

export const getResult = async (collection, doc) => {
  try {
    const resultRef = db.collection(collection);
    const result = await resultRef.doc(doc).get();

    if (result.exists) {
      return { data: result };
    } else {
      return { data: "Error retrieving document, as it doesnt exist" };
    }
  } catch (err) {
    if (err.response) {
      console.log(err.response.data);
      return err.response.data;
    } else if (err.request) {
      console.log(err.request);
      return err.request;
    } else {
      console.log(err.message);
      return err.message;
    }
  }
};

1
"If I purposely give a fake document ID, the catch function automatically takes over". This doesn't sound right. If doc doesn't exist then it won't throw an error. Can you please provide a screenshot of any error that you get in catch ? The existing code looks perfectly fine to me - Dharmaraj

1 Answers

0
votes

Is there a way I can easily check what type of error it is when I catch it?

The only piece of information you will get is the err object. We can't see what that is for your specific case, because we can't run your code. But it's what you'll have to use that object to figure out what the problem is and how to resolve it. These exception objects don't have a "type". You have to look at the contents of the object to understand what went wrong.

You might want to read up on exception handling in JavaScript. It is the same for all promises in JavaScript. Firestore is no different.