You need to enable JavaScript to run this app. 如何在Facebook Business Python SDK中捕获指定异常?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Facebook Business Python SDK中捕获指定异常?

解决方案

你确实需要额外导入异常相关的类,FacebookRequestError 定义在 facebook_business.exceptions 模块下,你之前导入的都是API实例和广告对象相关模块,异常类独立存放在exceptions模块下,所以无法从已导入的模块中找到对应的属性。

你只需要在脚本头部的导入区域新增一行导入语句即可:

from facebook_business.exceptions import FacebookRequestError

新增导入后你原本的异常捕获逻辑即可正常生效,另外建议你对捕获逻辑做优化,区分不同错误类型做处理,避免将参数错误、权限不足等非限流问题全部按限流处理,优化后的参考代码如下:

import time
from facebook_business.exceptions import FacebookRequestError

try:
    test = Ad(ad).get_insights()
except FacebookRequestError as e:
    error_code = e.api_error_code()
    # 匹配Facebook Marketing API常见限流相关错误码,可根据实际业务需求调整范围
    if error_code in (4, 17, 80004, 80005, 80008):
        print('Limit exceeded, wait for 10 minutes')
        time.sleep(600)
    else:
        # 其他类型错误输出信息后抛出,方便排查非限流问题
        print(f"Request failed, error code: {error_code}, error message: {e.api_error_message()}")
        raise

内容的提问来源于stack exchange,提问作者nikUoM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 07:30:04