Skip to content

Commit

Permalink
Fix the bug of httpx.ReadError and asyncio.CancelledError errors
Browse files Browse the repository at this point in the history
  • Loading branch information
yym68686 committed Aug 25, 2024
1 parent 55a4247 commit e6673ca
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,16 @@ def ensure_string(item):
else:
return str(item)

import asyncio
async def error_handling_wrapper(generator, status_code=200):
async def new_generator():
try:
yield ensure_string(first_item)
async for item in generator:
yield ensure_string(item)
except (httpx.ReadError, asyncio.CancelledError) as e:
logger.error(f"Network error in new_generator: {e}")
raise HTTPException(status_code=503, detail=f"Stream interrupted: {str(e)}")
except Exception as e:
logger.exception(f"Error in new_generator: {e}")
raise HTTPException(status_code=status_code, detail=f"Stream error: {str(e)}")
Expand All @@ -104,13 +108,15 @@ async def new_generator():
if isinstance(first_item_str, dict) and 'error' in first_item_str:
raise HTTPException(status_code=status_code, detail=f"{first_item_str}"[:300])

# 创建新的生成器并包装在 try-except 块中
wrapped_generator = new_generator()
try:
async for item in wrapped_generator:
yield item
except HTTPException as http_exc:
raise http_exc
except (httpx.ReadError, asyncio.CancelledError) as e:
logger.error(f"Network error during streaming: {e}")
raise HTTPException(status_code=503, detail=f"Stream interrupted: {str(e)}")
except Exception as e:
logger.exception(f"Unexpected error in error_handling_wrapper: {e}")
raise HTTPException(status_code=status_code, detail=f"Unexpected error: {str(e)}")
Expand Down

0 comments on commit e6673ca

Please sign in to comment.