[QUESTION] Only 500 response being received from middleware [ INVALID ]
See original GitHub issueFirst check
- [ YES ] I used the GitHub search to find a similar issue and didn’t find it.
- [ YES ] I searched the FastAPI documentation, with the integrated search.
- [ YES ] I already searched in Google “How to X in FastAPI” and didn’t find any information.
Description
I am trying to use middleware for Authorization ( Like Express JS in Node ). My middleware throws an exception which I am trying to send a custom response ( like 401 ) for, But I am only receiving 500 from the server.
From what I understand, The “middleware” raises an internal error that is not being over-ridden by my custom response. How can I over-ride the middleware’s default 500 response and send my own response?
Additional context
The middleware is below:
@add.middleware("http")
def validate_all_routes( request: Request, call_next):
try:
validate_route(request.headers) # Unauthenticated req --> Raises exception
response = call_next(request)
return { ... } # This return is received by client
except Exception as e:
return { "exception": "server_error" } # Not received by client
raise HttpException(status_code=401) # Not received by client
raise Response(status_code=401)
# ONLY IF I DO THIS
response = call_next(request)
return { ... } # Is the response that I sent received
`
Can someone please advise me on what I’m doing wrong and how I will be able to make the middleware send a custom response ( with custom HTTP_status) without invoking the
response = call_next(request)
Thanks for the help in advance! Let me know if I can provide any other context/ clues.
EDIT: I was facing 500 Internal Server Error because I did not use async
on the function below the middleware ie @app.middleware('http')
. Following @phy25’s comment on using `return Response(…) allows me to send a response with my own status_code
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (1 by maintainers)
Top GitHub Comments
yeah not saying it is super important but it is less than ideal. Expected behaviour is to handle errors in a similar manner across the FastApi handling code otherwise have to manually create a 401 response in middleware and use different implementation if triggered elsewhere.
Regarding unexpected exceptions that does sound bad, I’m not saying all exceptions should be safely handled rather the inbuilt
HTTPException
class which containsstatus_code
be handled the same way as in the query functions.:edit or at least update the docs around eror handling to say they don’t apply to middleware https://fastapi.tiangolo.com/tutorial/handling-errors/
Have you tried
return Response(content="", status_code=401)
?