0
votes

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('[email protected]', '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('[email protected]', '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!

1

1 Answers

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

this will give you as a result : EMAIL_EXISTS