Closed Kludex closed 1 month ago
This looks great! What happens if you raise the exception after accepting? I assume it's unchanged and basically undefined behavior, but it would be nice to document and maybe give users an informative error in the future?
Good question. And actually... This PR solves a problem that is happening on master:
from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.routing import WebSocketRoute
from starlette.websockets import WebSocket
async def ws_endpoint(websocket: WebSocket):
await websocket.accept()
raise HTTPException(status_code=400, detail="Bad request")
app = Starlette(routes=[WebSocketRoute("/ws", ws_endpoint)])
The connection stays open...
With this PR, we can see a server exception, given that the HTTPException
will try to send a 'websocket.http.response.start'
on the ExceptionMiddleware
:
maybe give users an informative error in the future?
We can do that, yep.
That's great! We can merge this as is then or if you want to add a slightly better error message for that case feel free to do so.
That's great! We can merge this as is then or if you want to add a slightly better error message for that case feel free to do so.
I think we have an issue on the wrap_app_handling_exceptions
where if I'm creating a Starlette application the function will be called twice (the first middleware, and the router), and then the response_start
will always be False
. And I need a similar logic to check if websocket_accepted
... In any case, I'll check later.
Before the
websocket.accept()
is called, we can actually return a different response... Right now it can be done withwebsocket.send_denial_response()
, which I'm not sure it was the best choice of API, maybe we shouldn't have added that method, but just used theHTTPException
.Reviews are welcome. I want to make a release on October 15.