如何在Python批量写入BigQuery时捕获并忽略异常以保证后续任务运行
问题原因
你当前只捕获了exceptions.BigQueryException类型的异常,但df.to_gbq方法运行时抛出的异常类型远不止这一种:
- 数据格式不符合要求时大概率抛出
ValueError或pandas-gbq库自带的GenericGBQException - 接口请求报错时会抛出GoogleAPI核心库的
GoogleAPIError子类(比如参数错误、权限不足等)
这些异常都不在你当前的捕获范围内,所以会直接终止程序。
解决步骤
- 先调试确认异常类型
你可以临时修改异常捕获逻辑,输出完整的异常信息,确认你遇到的报错对应的具体异常类:
try: logging.info(f'Writing {table_name} to BigQuery. Write disposition set to {write_disposition}') df.to_gbq(destination_table=table_id, credentials=CREDENTIALS, if_exists=write_disposition) # Confirm the write succeeded table_exists = confirm_bq_table_exists(bq_client, dataset_id, table_name) if table_exists: logging.info(f'The table {table_name} was written to BigQuery') return True except Exception as e: logging.info(f'捕获到异常,类型:{type(e).__name__},内容:{e}') pass
- 针对性调整捕获范围
调试确认异常类型后,把对应的异常类加到你的except捕获列表中即可,常见的需要捕获的异常导入方式如下:
# 导入pandas-gbq自定义异常 from pandas_gbq.exceptions import GenericGBQException # 导入Google云API通用异常 from google.api_core.exceptions import GoogleAPIError
修改后的异常捕获块示例:
except (GenericGBQException, GoogleAPIError, ValueError) as e: logging.info(f'The write attempt failed with the exception {e}') pass
注意:不建议长期直接捕获所有
Exception,确认具体异常类型后尽量收窄捕获范围,避免漏掉内存溢出、进程被终止这类需要中断运行的严重错误。
内容的提问来源于stack exchange,提问作者GDB
相关产品推荐
相关产品推荐

