如何在Python中处理Google API错误

32 投票
2 回答
30310 浏览
提问于 2025-04-18 08:00

我现在在做很多关于BigQuery的事情,使用了很多try... except...的代码。看起来我从BigQuery得到的几乎每个错误都是一种叫做apiclient.errors.HttpError的错误,不过它们后面附带的字符串各不相同,比如:

<HttpError 409 when requesting https://www.googleapis.com/bigquery/v2/projects/some_id/datasets/some_dataset/tables?alt=json returned "Already Exists: Table some_id:some_dataset.some_table">

<HttpError 404 when requesting https://www.googleapis.com/bigquery/v2/projects/some_id/jobs/sdfgsdfg?alt=json returned "Not Found: Job some_id:sdfgsdfg">

还有很多其他的错误。目前我能想到的处理这些错误的方法就是对错误信息进行正则表达式匹配,但这样做很麻烦,肯定不是最好的办法。有没有更好的处理方式呢?

2 个回答

14

谷歌云现在提供了异常处理器:

from google.api_core.exceptions import AlreadyExists, NotFound
try:
    ...
except AlreadyExists:
    ...
except NotFound:
    ...

这样可以更准确地捕捉到错误的具体信息。

请参考这个源代码,了解其他可以使用的异常类型:http://google-cloud-python.readthedocs.io/en/latest/_modules/google/api_core/exceptions.html

51

BigQuery 是一个基于 REST 的接口,它的错误信息遵循标准的 HTTP 错误规则。

在 Python 中,HttpError 有一个叫 resp.status 的字段,可以返回 HTTP 状态码。就像你上面提到的,409 代表“冲突”,404 代表“未找到”。

举个例子:

from googleapiclient.errors import HttpError
try:
   ...
except HttpError as err:
  # If the error is a rate limit or connection error,
  # wait and try again.
  if err.resp.status in [403, 500, 503]:
    time.sleep(5)
  else: raise

响应结果也是一个 JSON 对象,更好的方法是解析这个 JSON,然后查看错误原因字段:

if err.resp.get('content-type', '').startswith('application/json'):
    reason = json.loads(err.content).get('error').get('errors')[0].get('reason')

这些错误原因可能包括:未找到(notFound)、重复(duplicate)、访问被拒绝(accessDenied)、查询无效(invalidQuery)、后端错误(backendError)、资源超限(resourcesExceeded)、无效(invalid)、配额超限(quotaExceeded)、速率限制超限(rateLimitExceeded)、超时(timeout)等等。

撰写回答