python - 捕获 Python 云存储错误
问题描述
我目前正在检查 Cloud Run 应用程序的错误处理,我注意到它没有像我希望的那样捕获错误并优雅地退出。考虑以下:
bucket = storage_client.bucket(input_bucket)
try:
blob = bucket.get_blob(input_file)
except Exception as e:
logger.log_struct(
{"ext_file_id": ext_file_id,
"output_bucket": output_bucket,
"status": "Failure",
"error_message": e,
"tags": tags},
resource=res, severity='ERROR')
return ("", 400)
对于我的测试,我特意从存储桶中删除了服务帐户权限。在本地测试时:
try:
blob = blob = bucket.get_blob(input_file)
except Exception as e:
print(e)
这将按预期返回错误消息:“403 GET https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/[BLOB_NAME]?projection=noAcl&prettyPrint=false : [ServiceAccount@...]没有 storage.objects.get 访问 Google Cloud Storage 对象的权限。”
但是,我上面的代码并没有像我预期的那样给我结构化的错误日志;相反,它会产生很长的回溯,然后继续重现错误,直到我清除触发 Cloud Run 的 Pub/Sub。
我尝试使用异常模块(来自 google.cloud import storage, exceptions),但如何使用它并不是特别清楚:
try:
blob = blob = bucket.get_blob(input_file)
except exceptions.Forbidden:
print(exceptions.Forbidden) # This give me the object
print(exceptions.Forbidden.code) # This gives me HTTPStatus.FORBIDDEN
但是,如果我重新打印exceptions.Forbidden.code,它会给我:<HTTPStatus.FORBIDDEN: 403>。
如果我可以让 403 HTTPStatus 最初显示,我可能会使用它,但理想情况下,无论收到什么 HTTP 错误消息(404,403 等),我都需要捕获错误消息并显示结构化错误。
解决方案
下面是一个简单的示例,用于确定异常google-api-core
具有哪些属性,使用 python 内置dir()
函数。阅读材料。
您感兴趣的是公共的,例如没有前导下划线...
from google.cloud import exceptions
from pprint import pprint
try:
raise exceptions.NotFound('message goes here')
except Exception as e:
pprint(dir(e))
print()
print(e.message)
输出:
['__cause__',
'__class__',
'__context__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__setstate__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__suppress_context__',
'__traceback__',
'__weakref__',
'_errors',
'_response',
'args',
'code',
'errors',
'grpc_status_code',
'message',
'response',
'with_traceback']
message goes here
推荐阅读
- python - 设置具有多个要求的变量
- c# - 引发了未处理的异常。无法使用 .NetCore 3.1 在 Azure AppService 上加载文件或程序集 Newtonsoft.Json Version=12.0.0.0
- javascript - 用户操作后重新加载数据表中的表
- azure-storage-files - 使用 Azure Logic App 删除 Azure 文件共享中的旧文件
- android - Android Studio 中的“立即同步”按钮在哪里?
- powershell - Powershell - 为所有用户获取桌面路径 [OneDrive Sync on them]
- italic - 如何将不同的样式添加到 HTML 中一行的不同部分并将所有内容一起打印?
- javascript - 如何正确搜索 JavaScript 对象并将其从一个 js 文件推送到另一个 js 文件的数组中?
- excel - 如何清除excel中的内容?
- php - 有没有办法通过 php 从 html 表中获取产品的平均价格并将结果作为最后一行添加到该表中?