Raise instead a return
Question:
Can anybody help me to understand why not raise an HTTPException
when the status is 200 instead a return
?
working with fastApi
A code as example:
@app.delete("/delete")
def delete(id = Query(...,description="Delete ID to be deleted")):
if id not in dictionary:
raise HTTPException(status_code=404,detail="Delete Id doesn't exists.")
del dictionary[id]
return {"Success":"Delete deleted!"}
I want to understand why not to use as example:
raise HTTPException(status_code=200,detail="Delete deleted!")
Is this a correct way to use it?
Answers:
First of all because of the semantics: an exception is a language construct that means something else than returning the result of a function. It breaks the normal flow of the FastAPI application, and I’m guessing it will/could break most middleware handling (such as CORS headers) because suddenly an exception has occurred instead.
Secondly: Because you probably want to return something else than just information under a detail
key. It won’t be able to use the response_model
mechanism that’s built-in to FastAPI and allows you to tweak and validate the response model for each type of request declaratively (i.e. by configuring the view decorator).
- return is better
- A lot of times the result should be equal
- raise breaks all next middlewares (pre, mid, post)
- Here is redirect login page middleware
class Middleware(APIRoute):
def get_route_handler(self) -> Callable:
original_route_handler = super().get_route_handler()
async def custom_route_handler(req: Request) -> Response:
try:
res: Response = await original_route_handler(req) #original request
except HTTPException as e: #catch login exception
if e.status_code == status.HTTP_403_FORBIDDEN:
return RedirectResponse(url = Const.DEFAULT_PAGE) #redirect to home page
else:
raise e #other exception process normally
return res
return custom_route_handler
Can anybody help me to understand why not raise an HTTPException
when the status is 200 instead a return
?
working with fastApi
A code as example:
@app.delete("/delete")
def delete(id = Query(...,description="Delete ID to be deleted")):
if id not in dictionary:
raise HTTPException(status_code=404,detail="Delete Id doesn't exists.")
del dictionary[id]
return {"Success":"Delete deleted!"}
I want to understand why not to use as example:
raise HTTPException(status_code=200,detail="Delete deleted!")
Is this a correct way to use it?
First of all because of the semantics: an exception is a language construct that means something else than returning the result of a function. It breaks the normal flow of the FastAPI application, and I’m guessing it will/could break most middleware handling (such as CORS headers) because suddenly an exception has occurred instead.
Secondly: Because you probably want to return something else than just information under a detail
key. It won’t be able to use the response_model
mechanism that’s built-in to FastAPI and allows you to tweak and validate the response model for each type of request declaratively (i.e. by configuring the view decorator).
- return is better
- A lot of times the result should be equal
- raise breaks all next middlewares (pre, mid, post)
- Here is redirect login page middleware
class Middleware(APIRoute):
def get_route_handler(self) -> Callable:
original_route_handler = super().get_route_handler()
async def custom_route_handler(req: Request) -> Response:
try:
res: Response = await original_route_handler(req) #original request
except HTTPException as e: #catch login exception
if e.status_code == status.HTTP_403_FORBIDDEN:
return RedirectResponse(url = Const.DEFAULT_PAGE) #redirect to home page
else:
raise e #other exception process normally
return res
return custom_route_handler