Home > Net >  How to handle errors with firebase admin sdk for Go?
How to handle errors with firebase admin sdk for Go?

Time:12-23

New to Go and trying to understand how to access the error details. I've already created a user, and now I'm expecting to get a "email-already-exists" error:

    fbUser, err := s.auth.CreateUser(ctx, fbUserParams)
    if err != nil {
        return nil, errors.New("[email] already exists") // <- it could be any other error, and I want to be able to handle it
    }

Here's what I see in my debugger:

enter image description here

How can I handle the error so that I can get the Code from it?

CodePudding user response:

I think that the best option you have is using the Errors.As function. You can learn more about it at here: https://pkg.go.dev/errors#As
The error returned by Google Firebase is of type FirebaseError that involves two properties: Code and String. You can try with the following code snippet:

fbUser, err := s.auth.CreateUser(ctx, fbUserParams)
if err != nil {
    var firebaseErr *FirebaseError
    if errors.As(err, &firebaseErr) {
        // here you can access "Code" and "String"
    } else {
        return nil, errors.New("[email] already exists")
    }
}

Thanks to this code you should be able to manage what you need. Pay attention to import correctly the package that provides the type FirebaseError. Maybe read something on the Firebase documentation first.
Hope this helps!

  • Related