Matthew Keller
Matthew Keller

Reputation: 463

Importing AuthError in TypeScript using Firebase

Is there a way I can check if an error is of type "AuthError" in TypeScript when using Firebase.

I have an Https Callable function that has a try/catch block that includes the following:

try{
    await admin.auth().getUser(data.uid); // will throw error if user does not exist
    await admin.auth().deleteUser(data.uid);
} catch (error) {
    if(error instanceof AuthError) { // error here
        if (error.code === "auth/user-not-found") {
            logger.error(`Error: auth/user-not-found, Given user ID does not exist in Firebase Authentication`);
            throw new https.HttpsError("not-found", "Given user ID does not exist in Firebase Authentication");
        }
    }
}

But I will get an error in my IDE at the if statement:

'AuthError' only refers to a type, but is being used as a value here.ts(2693)

I am using import { AuthError } from "firebase/auth"; to import AuthError.

Is there a way to check if the error is an instance of AuthError? Are my imports correct? I could find no helpful information in the documentation

Thank you

Upvotes: 6

Views: 1899

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317392

The API docs you linked to are for the node.js client SDK. That's not the same as the Firebase Admin SDK for node.js that you're code is calling into. The admin SDK just doesn't throw that AuthError, nor does it declare anywhere the type of the error object, even in its own API docs for getUser.

If you look at the Admin SDK documentation, it says:

If the provided email does not belong to an existing user or the user cannot be fetched for any other reason, the Admin SDK throws an error. For a full list of error codes, including descriptions and resolution steps, see Admin Authentication API Errors.

If you dig further into the source code, you'll see that it actually throws a FirebaseAuthError object, which doesn't appear in the public API documentation. So, it appears you're on your own if you want a typesafe error. But you can always just reach into the properties of that object to find out more.

Upvotes: 6

Related Questions