使用PRAW开发Reddit bot时迭代异常对象提示不可迭代如何解决
问题原因
PRAW 定义的 RedditAPIException 是自定义异常类,仅单独实现了 __contains__ 方法支持字符串匹配判断(所以你之前写的 if "keyword thats in the error" in e 可以正常运行),但没有实现 __iter__ 迭代协议,因此无法直接遍历对象内容。
你尝试的 str(e) 方法不生效,是因为该自定义异常的 __str__ 方法仅返回极简的错误描述,甚至部分场景下返回空值,无法拿到完整错误内容用于遍历。
解决方案
方案1:提取异常内置错误信息拼接后遍历
RedditAPIException 内置了 items 属性,存储了接口返回的所有错误条目,你可以先把所有错误信息拼接为完整字符串,再遍历字符:
try: # 你的PRAW相关业务代码 except Exception as e: error_full_text = "" # 适配RedditAPIException的错误提取 if hasattr(e, "items"): for err_item in e.items: error_type, err_msg, *extra = err_item error_full_text += f"错误类型:{error_type},错误信息:{err_msg}\n" else: # 其他类型异常直接转字符串 error_full_text = str(e) # 遍历字符实现业务需求 character_num = 0 for character in error_full_text: character_num += 1 print(f"{character_num}: {character}")
如果仅需要判断是否存在指定关键词,不需要遍历字符,直接用 if "目标关键词" in error_full_text: 即可,执行效率更高。
方案2:强制序列化异常对象后遍历
如果不需要拆分错误条目,仅需要拿到完整的异常描述,可以直接用 repr() 方法强制序列化异常对象,再遍历结果字符串:
try: # 你的业务代码 except Exception as e: error_str = repr(e) character_num = 0 for character in error_str: character_num += 1 print(f"{character_num}: {character}")
repr() 方法会返回完整的对象描述,包含所有属性内容,不会丢失异常信息。
内容的提问来源于stack exchange,提问作者Anonyo Noor
相关产品推荐
相关产品推荐

