如何在Python中管理Google API错误

2024-05-10 19:32:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用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">

在许多其他人中。现在,我看到的处理这些问题的唯一方法是对错误消息运行regex,但这很混乱,绝对不理想。有更好的办法吗?


Tags: httpscomidwww错误somebigquerydataset
2条回答

谷歌云现在提供异常处理程序:

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

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、ResourcesXceedd、invalid、quotaExceeded、rateLimitExceeded、timeout等

相关问题 更多 >