encode / starlette

The little ASGI framework that shines. 🌟
https://www.starlette.io/
BSD 3-Clause "New" or "Revised" License
10.3k stars 946 forks source link

Allow to raise `HTTPException` before `websocket.accept()` #2725

Closed Kludex closed 1 month ago

Kludex commented 1 month ago

Before the websocket.accept() is called, we can actually return a different response... Right now it can be done with websocket.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 the HTTPException.

Reviews are welcome. I want to make a release on October 15.

Kludex commented 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...

Screenshot 2024-10-13 at 19 06 19

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:

Screenshot 2024-10-13 at 19 08 06
Kludex commented 1 month ago

maybe give users an informative error in the future?

We can do that, yep.

adriangb commented 1 month ago

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.

Kludex commented 1 month ago

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.