How to handle exceptions ? #375
-
First Check
Commit to Help
Example Codeimport asyncer
import logging
from typing import Union
from fastapi import FastAPI
async def func1(name: str):
return {"message": f"Hello {name} form func1"}
async def func2():
return {"message": f"Hello {name} form func2"}
@app.get("/test")
async def knowledge_panel(name_str: str):
async with asyncer.create_task_group() as task_group:
try:
soon_value1 = task_group.soonify(func1)(name=name_str)
except Exception:
logging.exception()
try:
soon_value2 = task_group.soonify(func2)(name=name_str)
except Exception:
logging.exception()
data = [soon_value1.value, soon_value2.value]
return data Description
Operating SystemWindows Operating System DetailsNo response asyncer Version0.0.1 Python VersionPython 3.10.5 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
I assume you solved it, thanks for closing the issue 👍 |
Beta Was this translation helpful? Give feedback.
-
@tiangolo not actually, I tried something else but it's not that robust and clean. |
Beta Was this translation helpful? Give feedback.
-
@sumit-158 how did you handle this? I'm having the exact same problem and can't find anything about it. |
Beta Was this translation helpful? Give feedback.
-
@gitierrez I used an async "exception_wrapper" decorator. |
Beta Was this translation helpful? Give feedback.
-
I see there 3 options:
async def func1(name: str):
try:
return {"message": f"Hello {name} form func1"}
except:
return {} # fallback value
...
def catch(func):
async def wrapped(*args, **kwargs):
try:
return await func(*args, **kwargs)
except:
return None
return wrapped
# apply decorator
@catch
def func1(...):
...
def func2(...):
...
@app.get("/test")
async def knowledge_panel(name_str: str):
async with asyncer.create_task_group() as task_group:
soon_value1 = task_group.soonify(func1)(name=name_str) # catch applied to all func1
soon_value2 = task_group.soonify(catch(func2))(name=name_str) # or wrap inly exact call
data = [soon_value1.value, soon_value2.value] # don't forget to handle None case
return data
@app.get("/test")
async def knowledge_panel(name_str: str):
try:
async with asyncer.create_task_group() as task_group:
soon_value1 = task_group.soonify(func1)(name=name_str)
soon_value2 = task_group.soonify(func2)(name=name_str)
data = [soon_value1.value, soon_value2.value]
except:
data = []
return data |
Beta Was this translation helpful? Give feedback.
I see there 3 options: