Search code examples
node.jstypescriptfirebasegoogle-cloud-functionsfirebase-admin

How can I catch a firebase auth error with firebase admin


I have the following try catch

try {
  user = await admin.auth().getUserByEmail(inputEmail);
} catch (error) {
  if(error.code !== "auth/user-not-found") throw new Error("authentication failed");
}

But I get an an error saying

Object is of type 'unknown'.

On error.code

This code was working perfectly fine before. How can this be solved?

I found the this

https://firebase.google.com/docs/reference/js/v8/firebase.FirebaseError

but I do not know where I can import it from.

enter image description here

I tried to asign any as type enter image description here

And I tried to check if the error was a instance of Error which says

Property 'code' does not exist on type 'Error'.

enter image description here


Solution

  • The error simply says that type of error is unknown.

    try {
      // ...
    } catch (error: unknown) {
      // unknown --> ^^^
    }
    

    If you are using Typescript 4.4 then you can use --useUnknownInCatchVariables flag which changes the default type of catch clause variables from any to unknown.

    Then you set up User defined type guards to specify type for the error that is being thrown. You can import FirebaseError from @firebase/util as in this issue.

    import { FirebaseError } from '@firebase/util';
    
    try {
      // ...
    } catch (error: unknown) {
      if (error instanceof FirebaseError) {
         console.error(error.code)
      }
    }