In this post, we delve into the management of exceptions in WebSockets, focusing on a potent but often
overlooked feature: the WebSocketException offered by Starlette.
Understanding WebSocketException
Conceptually, WebSocketException enables you to close a WebSocket connection with a specific code and reason
by raising this exception in your WebSocket route. Here's an illustrative example:
fromfastapiimportFastAPI,WebSocketfromfastapi.exceptionsimportWebSocketExceptionapp=FastAPI()@app.websocket("/ws")asyncdefwebsocket_endpoint(websocket:WebSocket):awaitwebsocket.accept()raiseWebSocketException(code=1008,reason="Closing the connection...")
In this instance, a WebSocketException is raised bearing the code 1008 and the explicit reason for closure: "Closing the connection...".
To run this application, first install FastAPI, Uvicorn, and WebSockets:
pipinstallfastapiuvicornwebsockets
Run the application using Uvicorn:
uvicorn main:app --reload
On opening a WebSocket connection to ws://localhost:8000/ws, you will find the connection being closed with focal code
1008 and the attributed reason.
I use wscat for testing WebSocket connections; you can install it with the following command:
npminstall-gwscat
A connection is opened with:
wscat-cws://127.0.0.1:8000/ws
Handle custom exceptions
The app.exception_handler can be used to handle custom exceptions. Consider the following sample: