当试图访问GCP存储中的文件时,如何正确处理从get_bucket()函数引发的错误



目标

我想使用python访问和修改GCP存储桶中的一个文件。

我实现了这个代码:

def get_file_from_bucket(file_name, bucket_name):
# get storage client
storage_client = storage.Client()
# get bucket with name
bucket = storage_client.get_bucket(bucket_name)
# get bucket data as blob
blob = bucket.get_blob(file_name)
# convert to text
text = blob.download_as_text()
return text

它运行良好。我可以访问该文件。

问题

如果在GCP存储中以某种方式删除了bucket,我的代码在尝试访问它时会引发一个错误:

  • 当bucket不存在时,google.api_core.exceptions.NotFound: 404 GET {link_to_my_file}: The specified bucket does not exist.将被提升

我知道我需要用try except来捕捉错误,但我也知道裸异常不是一个好的做法,而且由于我找不到可能引发的错误的任何细节,我不知道该怎么做。

try:
# get bucket with name
bucket = storage_client.get_bucket(bucket_name)
except Exception:    ----> what kind of exception should I place here ?
do_stuff()

问题

尝试使用Python访问GCP存储中的文件时,如何处理错误?

我应该预料到什么样的错误?他们有多少?

额外的问题:我在哪里可以找到关于这方面的准确文档?这似乎是过时的

在文档中找到:https://googleapis.dev/python/storage/latest/client.html#google.cloud.storage.client.Client.get_bucket

代码:

try:
bucket = client.get_bucket("my-bucket")
except google.cloud.exceptions.NotFound:
print("Sorry, that bucket does not exist!")

最新更新