0

使用 pyrebase 包装器进行 Firebase 身份验证,当尝试创建一个已经是用户的新用户时,pyrebase 会将 google API 响应包装在 HTTPError 消息中。但是当我尝试捕获此异常时,它不会将 HTTPError 识别为异常。expect Exception as e我可以通过使用下面更详细的 show来访问异常。

代码:

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)

这将输出:

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

如果我采取更一般的方法并使用,我可以捕捉到错误:

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

这将优雅地打印异常:

(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')

这给了我信息,但它是一个字符串。

如何访问异常消息中显示的响应 JSON?

谢谢!

4

1 回答 1

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

这会给你一个结果:EMAIL_EXISTS

于 2020-08-13T19:17:25.287 回答