首页 > 解决方案 > 捕获 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 等),我都需要捕获错误消息并显示结构化错误。

标签: pythonapigoogle-cloud-platformerror-handlinggoogle-cloud-storage

解决方案


下面是一个简单的示例,用于确定异常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

推荐阅读