【问题标题】:Get Pyrebase HTTPError information获取 Pyrebase HTTPError 信息
【发布时间】:2020-05-06 04:36:40
【问题描述】:

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

代码:

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?

谢谢!

【问题讨论】:

    标签: python flask pyrebase


    【解决方案1】:
    json.loads(e.args[1])['error']['message']
    

    这会给你一个结果:EMAIL_EXISTS

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 2019-11-16
      • 2011-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-30
      相关资源
      最近更新 更多