Fix the bug of httpx.ReadError and asyncio.CancelledError errors
Browse files
utils.py
CHANGED
|
@@ -73,12 +73,16 @@ def ensure_string(item):
|
|
| 73 |
else:
|
| 74 |
return str(item)
|
| 75 |
|
|
|
|
| 76 |
async def error_handling_wrapper(generator, status_code=200):
|
| 77 |
async def new_generator():
|
| 78 |
try:
|
| 79 |
yield ensure_string(first_item)
|
| 80 |
async for item in generator:
|
| 81 |
yield ensure_string(item)
|
|
|
|
|
|
|
|
|
|
| 82 |
except Exception as e:
|
| 83 |
logger.exception(f"Error in new_generator: {e}")
|
| 84 |
raise HTTPException(status_code=status_code, detail=f"Stream error: {str(e)}")
|
|
@@ -104,13 +108,15 @@ async def error_handling_wrapper(generator, status_code=200):
|
|
| 104 |
if isinstance(first_item_str, dict) and 'error' in first_item_str:
|
| 105 |
raise HTTPException(status_code=status_code, detail=f"{first_item_str}"[:300])
|
| 106 |
|
| 107 |
-
# 创建新的生成器并包装在 try-except 块中
|
| 108 |
wrapped_generator = new_generator()
|
| 109 |
try:
|
| 110 |
async for item in wrapped_generator:
|
| 111 |
yield item
|
| 112 |
except HTTPException as http_exc:
|
| 113 |
raise http_exc
|
|
|
|
|
|
|
|
|
|
| 114 |
except Exception as e:
|
| 115 |
logger.exception(f"Unexpected error in error_handling_wrapper: {e}")
|
| 116 |
raise HTTPException(status_code=status_code, detail=f"Unexpected error: {str(e)}")
|
|
|
|
| 73 |
else:
|
| 74 |
return str(item)
|
| 75 |
|
| 76 |
+
import asyncio
|
| 77 |
async def error_handling_wrapper(generator, status_code=200):
|
| 78 |
async def new_generator():
|
| 79 |
try:
|
| 80 |
yield ensure_string(first_item)
|
| 81 |
async for item in generator:
|
| 82 |
yield ensure_string(item)
|
| 83 |
+
except (httpx.ReadError, asyncio.CancelledError) as e:
|
| 84 |
+
logger.error(f"Network error in new_generator: {e}")
|
| 85 |
+
raise HTTPException(status_code=503, detail=f"Stream interrupted: {str(e)}")
|
| 86 |
except Exception as e:
|
| 87 |
logger.exception(f"Error in new_generator: {e}")
|
| 88 |
raise HTTPException(status_code=status_code, detail=f"Stream error: {str(e)}")
|
|
|
|
| 108 |
if isinstance(first_item_str, dict) and 'error' in first_item_str:
|
| 109 |
raise HTTPException(status_code=status_code, detail=f"{first_item_str}"[:300])
|
| 110 |
|
|
|
|
| 111 |
wrapped_generator = new_generator()
|
| 112 |
try:
|
| 113 |
async for item in wrapped_generator:
|
| 114 |
yield item
|
| 115 |
except HTTPException as http_exc:
|
| 116 |
raise http_exc
|
| 117 |
+
except (httpx.ReadError, asyncio.CancelledError) as e:
|
| 118 |
+
logger.error(f"Network error during streaming: {e}")
|
| 119 |
+
raise HTTPException(status_code=503, detail=f"Stream interrupted: {str(e)}")
|
| 120 |
except Exception as e:
|
| 121 |
logger.exception(f"Unexpected error in error_handling_wrapper: {e}")
|
| 122 |
raise HTTPException(status_code=status_code, detail=f"Unexpected error: {str(e)}")
|