【问题标题】:how do you catch exception with google cloud storage api你如何用谷歌云存储 api 捕捉异常
【发布时间】:2025-12-08 12:15:02
【问题描述】:

我似乎无法捕捉到这个异常,除非通过 catch-all

from google.cloud import storage, exceptions

def gsutil_ls(bucket_name, filter=None, project_id=None):
  try:
    client = storage.Client( project=project_id )
    bucket_path = "gs://{}/".format(bucket_name)
    bucket, err = client.get_bucket(bucket_name)
    files = ["{}{}".format(bucket_path,f.name) for f in bucket.list_blobs() ]
    if filter:
      files = [f for f in files if filter in f]
    # print(files)
    return files
  except exceptions.NotFound:
    raise ValueError("ERROR: GCS bucket not found, path={}".format(bucket_path))
  except Exception as e:
    print( e)



gsutil_ls("my-bucket", project_id="my-project")

返回:

400 GET https://www.googleapis.com/storage/v1/b/my-bucket?projection=noAcl: Invalid bucket name: 'my-bucket'

见:https://googlecloudplatform.github.io/google-cloud-python/latest/storage/client.html#google.cloud.storage.client.Client.get_bucket

【问题讨论】:

  • 我相信你在最后一个 except 子句中登陆 -- 如果你也打印 type(e) 怎么办?
  • 哇! <class 'google.api_core.exceptions.Forbidden'>

标签: google-cloud-storage jupyter-notebook google-colaboratory


【解决方案1】:

在这种情况下,对于:

400 GET https://www.googleapis.com/storage/v1/b/my-bucket?projection=noAcl: Invalid bucket name: 'my-bucket'

使用exceptions.Forbidden

  try:
     [...]
  except exceptions.Forbidden:
    raise ValueError("ERROR: GCS bucket not found, path={}".format(bucket_path))

【讨论】: