Tips for handling Firebase JS SDK errors within try-catch blocks

Attempting to type the err object in a function that saves documents to Firestore has been challenging.

async function saveToFirestore(obj: SOME_OBJECT, collection: string, docId: string) {
  try {
    await firebase.firestore().collection(collection).doc(docId).set(obj);
  }
  catch(err: firebase.firestore.FirestoreError) {
    // THIS DOESN'T SEEM TO BE POSSIBLE
  }
}

I also experimented with firebase.FirebaseError

The error I encounter looks like this:

https://i.sstatic.net/EDAWL.png

I'm wondering how to achieve autocomplete for the error object from Firebase. Should the error object always be typed as any or unknown? What is the preferred approach?


UPDATE

Since directly typing the catch(err) seems impossible, I was aiming for something like this:

catch(err) {
  if (err instanceof firebase.FirebaseError) {  // <--- THIS DOES NOT WORK
    throw `something for the FirebaseError`
  }
  else {
    throw `something else for other error types`
  }
}

However, according to the discussion on the issue shared by Frank in his answer, it appears that this approach is not feasible.

_We don't allow type annotations on catch clauses because there's really no way to know what type an exception will have. You can throw objects of any type and system generated exceptions (such as out of memory exception) can technically happen at any time. Even if we had a Java-like notion of throws annotations it is not clear that we could ever really rely on them. (And, it is also not clear that they work all that well in Java, but that's another discussion.)_

We don't narrow any in type guards unless we know the exact type you're narrowing to. For example, if you check typeof x === "string" we will indeed narrow an any to string because we know for sure that is the exact type of x. That isn't the case with instanceof. Specifically, you might check x instanceof Base, but x might actually be an instance of a class derived from Base. If we narrowed x to type Base you'd see errors on access to properties of the derived class even though there is nothing wrong with the code. Now, before you argue those errors would be fine, keep in mind that the declared type of x is any, so you've already said you want no checking. We take that as an indication that we should issue errors only when we're 100% sure they're errors. And we only know that if we know the exact type.

Answer №1

It is not possible to specify a type on a catch clause because the language does not allow for catching specific types of errors.

A common workaround is to declare a local variable immediately inside the catch block:

catch(e) {
  const error: firebase.firestore.FirestoreError = e;
}

For more information on this topic, you can refer to this discussion: https://github.com/microsoft/TypeScript/issues/8677#issuecomment-220385124

Answer №2

After giving it a shot, I managed to find the solution

I employed the instanceof operator

try {
  await signInWithCredential(auth, authProvider)
} catch (e) {
  const error = e instanceof FirebaseError
  if(error){
    console.log(e.code)
  }
}

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular2 - Showing parameters in modal interface

I am working on an Angular5 app and have a component.html file with a function called markerClick that opens a modal. However, I am facing challenges in displaying the item.lat parameter in the modal and would appreciate your assistance. Below is the code ...

Unable to simulate a static method in Vitest - encountering an error stating "is not a function"

I am currently writing unit tests using the Vitest framework for my TypeScript and React application, but I have encountered an issue with mocking static methods. Below is a snippet of my code: export class Person { private age: number; constructor(p ...

What causes the index to display [object Object] rather than an integer in React?

It has been a long time since I last worked with React, and now I'm facing an issue. Whenever I use console.log to display the index within the map function, my console output looks like this: https://i.stack.imgur.com/VbGmE.png However, the result ...

Bringing together the functionality of tap to dismiss keyboard, keyboard avoiding view, and a submit button

On my screen, there's a big image along with a text input and a button at the bottom. The screen has three main requirements: When the user taps on the input, both the input and button should be visible above the keyboard The user must be able to ta ...

React Router is used to render routes that do not match the specified path

I am utilizing TypeScript in React Router. I have defined two routes: / and /pages/id. class MyComponent extends React.Component { render() { return <BrowserRouter> <div> <Route exact path='/' ch ...

Enhance the design of MDX in Next.js with a personalized layout

For my Next.js website, I aim to incorporate MDX and TypeScript-React pages. The goal is to have MDX pages automatically rendered with a default layout (such as applied styles, headers, footers) for ease of use by non-technical users when adding new pages. ...

What is the best way to retrieve a variable that has been exported from a page and access it in _

Suppose this is my pages/visitor.tsx const PageQuery = 'my query'; const Visitor = () => { return <div>Hello, World!</div>; }; export default Visitor; How can I retrieve PageQuery in _app.tsx? One approach seems to be by assi ...

Retrieving data from the firebase database by filtering based on the child's specific value

Looking at the firebase database, I can see that only the 'name' field is available. Now, I am trying to retrieve the 'quantity' value associated with that specific 'name'. Can someone provide me with a sample firebase query i ...

Using both withNextIntl and withPlaiceholder simultaneously in a NextJS project causes compatibility issues

I recently upgraded to NextJS 14 and encountered an issue when deploying my project on Vercel. The next.config.mjs file in which I wrapped my nextConfig in two plugins seemed to prevent the build from completing successfully. As a workaround, I decided t ...

Unable to locate the name 'Cheerio' in the @types/enzyme/index.d.t file

When I try to run my Node application, I encounter the following error: C:/Me/MyApp/node_modules/@types/enzyme/index.d.ts (351,15): Cannot find name 'Cheerio'. I found a suggestion in a forum that recommends using cheerio instead of Cheerio. H ...

Issue with Angular data display in template

My Ionic app with Angular is fetching data in the constructor, but I am facing difficulties displaying it in the HTML. Code component receiver: any; constructor( //.... ) { // get receiver data const receiverData = this.activatedRoute.snapsho ...

iOS 10.3.1 causing Ionic 2 (click) event to trigger twice

I am currently working on an Ionic 2 app and I am facing an issue with the click event. When I test the app on a device and click on a button, let's say to trigger an alert, the function executes once. However, if I click on the button again, the fun ...

Updating and saving data in Ag-Grid with server communication

Is it possible to create a grid using Ag-Grid on Angular that fetches data from a local JSON file? And how can the edited row data be saved and sent to the server or back to the local JSON file? In summary, I would like to know how to save edited row data ...

Bring in typings from a package with an alternate title

I have a project that I am currently converting to typescript. In this project, I am using the package ng-idle. Additionally, there is a corresponding @types package named angular-idle, which contains the file @types/angular-idle/index.d.ts with the follow ...

Arrange the items that are missing from Array B to be located at the bottom of Array A, organized in a file tree structure

I have two arrays containing different types of objects. Each object in the arrays has a title assigned to it. My goal is to compare these two arrays based on their titles and move any files that are not included in the bottom part of the fileStructure arr ...

Traversing an array of objects in TypeScript and appending to a separate array if not already present

I have been given an array containing objects in the following format: export interface Part { workOrder?: string; task?: string; partNumber?: string; qty?: number; image?: string; name?: string; } My goal is to loop through each object in th ...

Ways to toggle checkboxes to show or hide their child items and subitems

I'm working on creating a straightforward menu that allows users to click on a parent checkbox to expand or collapse its children. The challenge I'm facing is how to make the parent checkboxes expand while hiding the children items within them wh ...

Different ways to determine if a given string exists within an Object

I have an object called menu which is of the type IMenu. let menu: IMenu[] = [ {restaurant : "KFC", dish:[{name: "burger", price: "1$"}, {name: "french fries", price: "2$"}, {name: "hot dog", d ...

The error message TS2304 is indicating that the name 'Set' cannot be found in electron-builder

I am trying to utilize the AppUpdater feature in electron-builder for my Electron Application. Upon importing the updater in my main.ts file: import { autoUpdater } from "electron-updater" An error is triggered when running the application: node_module ...

Is there a way to locate a prior version of the NPM @types package?

Currently, I am utilizing Angular version 1.4.7 and in need of a type file corresponding to this specific version. Browsing through the NPM website, I came across a type file for AngularJs listed as version 1.5.14 alpha. Is there a way to access a compreh ...