python - 获取 Pyrebase HTTPError 信息
问题描述
使用 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?
谢谢!
解决方案
json.loads(e.args[1])['error']['message']
这会给你一个结果:EMAIL_EXISTS
推荐阅读
- typescript - 量角器 + 茉莉花 + TS。打字问题:xit 返回无效。如何使用 xit().pend(原因)
- vba - 选择现有形状时出现错误 86db089e
- java - 如何在java中获取表情符号代码?
- reactjs - 道具类型在反应应用程序中不起作用
- android - Android - DreamService 中的 setRequestedOrientation
- node.js - 错误:使用 fs.outputJsonSync 时没有这样的文件
- javascript - Location.go 后重新加载 Angular 6 路由参数
- truetype - True Type 字体缩放
- vba - 使用 VBA 复制并粘贴到新的表格行
- docker - 如何在 docker 中启用 udev 规则