Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 421
anonymous-dev Avatar asked Oct 21 '25 19:10

anonymous-dev


2 Answers

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)
  }
}
like image 195
Dharmaraj Avatar answered Oct 23 '25 11:10

Dharmaraj


Can you try it with this:

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

Pls check this docs about it.

like image 39
Tarik Huber Avatar answered Oct 23 '25 12:10

Tarik Huber