0

Using the pyrebase wrapper for Firebase Authentication, when attempting to create a new user that is already a user pyrebase wraps the google API response in an HTTPError message. But when I try to capture this exception it doesn't recognize HTTPError as an exception. I can access the exception by using expect Exception as e show in greater detail below.

Code:

config = {
  "apiKey": os.environ.get('WEB_API_KEY'),
  "authDomain": "project.firebaseapp.com",
  "databaseURL": "https://project.firebaseio.com",
  "storageBucket": "project.appspot.com",
  "serviceAccount": os.environ.get('FIREBASE_APPLICATION_CREDENTIALS')
}

firebase = pyrebase.initialize_app(config)

auth = firebase.auth()

# Attempt to register a user that already exists
try:
    user = auth.create_user_with_email_and_password('myemail@email.com', 'mypassword')
except HTTPError as e:
    print('Handling HTTPError:', e)

This will output:

Traceback (most recent call last):
  File "<console>", line 3, in <module>
NameError: name 'HTTPError' is not defined

I can catch the error if i take a more general approach and use:

try:
    user = auth.create_user_with_email_and_password('myemail@email.com', 'mypassword')
except Exception as e:
    print(e.args)

This will then gracefully print the exception:

(HTTPError('400 Client Error: Bad Request for url: https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=<WEB_API_KEY>'), '{\n  "error": {\n    "code": 400,\n    "message": "EMAIL_EXISTS",\n    "errors": [\n      {\n        "message": "EMAIL_EXISTS",\n        "domain": "global",\n        "reason": "invalid"\n      }\n    ]\n  }\n}\n')

This gives me the info, but it is a string.

How do I access the response JSON that is shown in the Exception message?

Thanks!

Justin B
  • 51
  • 5

2 Answers2

3
json.loads(e.args[1])['error']['message']

this will give you as a result : EMAIL_EXISTS

0

For your case, try it, with firebase-admin==6.0.0:

import firebase_admin

try:
    user = auth.create_user_with_email_and_password('myemail@email.com', 'mypassword')
except firebase_admin._auth_utils.EmailAlreadyExistsError as e:
    print('Handling HTTPError:', e)
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 25 '22 at 07:51
  • Please consider adding some explanation describing how it solves the problem. – Azhar Khan Nov 28 '22 at 05:51