I developed some API endpoints using FastAPI. These endpoints are allowed to run BackgroundTasks
. Unfortunately, I do not know how to handle unpredictable issues from theses tasks.
An example of my API is shown below:
# main.py
from fastapi import FastAPI
import uvicorn
app = FastAPI()
def test_func(a, b):
raise ...
@app.post("/test", status_code=201)
async def test(request: Request, background_task: BackgroundTasks):
background_task.add_task(test_func, a, b)
return {
"message": "The test task was successfully sent.",
}
if __name__ == "__main__":
uvicorn.run(
app=app,
host="0.0.0.0",
port=8000
)
# python3 main.py to run
# fastapi == 0.78.0
# uvicorn == 0.16.0
Can you help me to handle any type of exception from such a background task?
Should I add any exception_middleware
from Starlette, in order to achieve this?