python runtime_error ai_generated true

RuntimeError: async generator raised StopAsyncIteration

ID: python/starlette-async-iterator-exhausted

Also available as: JSON · Markdown · 中文
80%Fix Rate
81%Confidence
0Evidence
2024-09-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active
3.11 active

Root Cause

Starlette 的异步生成器在迭代过程中被提前关闭或耗尽

generic

中文

Starlette 的异步生成器在迭代过程中被提前关闭或耗尽

Workarounds

  1. 90% success 确保异步生成器正确使用 async for 循环
    async for item in async_generator():
        process(item)
  2. 85% success 在调用处捕获 StopAsyncIteration
    try:
        async for item in gen:
            ...
    except StopAsyncIteration:
        pass

Dead Ends

Common approaches that don't work:

  1. 在生成器函数中添加 try-except 捕获 StopAsyncIteration 80% fail

    生成器内部不应捕获此异常,会导致状态混乱

  2. 使用同步生成器替代 70% fail

    破坏了异步上下文,可能阻塞事件循环