如何在Python中管理Google API错误

时间:2014-05-30 01:45:57

标签: python google-api google-bigquery

我目前正在使用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 个答案:

答案 0 :(得分:18)

BigQuery是一个REST API,它使用的错误遵循标准的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等。

答案 1 :(得分:5)

Google Cloud现在提供了异常处理程序:

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