New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
✨ Add exception handler for WebSocketRequestValidationError
(which also allows to override it)
#6030
Conversation
Update Starlette to 0.21.0 for WebSocket error handlng support
📝 Docs preview for commit 0d755c2 at: https://63f616c20ad18a14fc03c9eb--fastapi.netlify.app |
btw, Is there a way to make the fastapi exception_handler support websocket connection? It seems that when the websocket route is processing Depends, if an exception occurs in the Depends func, the exception will be handed over to the default ServerErrorMiddleware app = FastAPI()
@app.exception_handler(Exception)
async def exception_handler(request: Request | WebSocket, exc: Exception | ExceptionBase):
... venv/Lib/site-packages/starlette/middleware/errors.py:148 class ServerErrorMiddleware:
def __init__(
self,
app: ASGIApp,
handler: typing.Optional[typing.Callable] = None,
debug: bool = False,
) -> None:
...
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return |
I've been looking at that, over in the starlette repo. Basically, There may be a few reasons for this:
That being said, I'm in the process of investigating how standard servers deal with an unhandled exception in the websocket ASGI scope. Maybe Starlette could do with a separate webockets handler inside ServerErrorMiddleware in this case. |
Oh, and by the way, the |
📝 Docs preview for commit 72d8584 at: https://641c15416cec180f2f6f008d--fastapi.netlify.app |
📝 Docs preview for commit 37e9c97 at: https://6457867e077e6b51a52b19cd--fastapi.netlify.app |
WebSocketRequestValidationError
(which also allows to override it)
Awesome, thanks @kristjanvalur! 🚀 This will be available in the next release, in the next hours (or tomorrow), |
Previously, when a WebSocket dependency failed, the connection was closed (via
close()
) and aWebSocketRequestValidationError
was raised.While the
close()
was typically handled, and would result in a server returning 403 to the originator (as per ASGI spec https://asgi.readthedocs.io/en/latest/specs/www.html?highlight=403#close-send-event), a subsequently raised exception was not handled and would typically result in an internal 500 error. This error could pollute logs and generally be a nuisance.Starlette
has, since version 0.21.0, supported error handlers for WebSocket endpoints. This PR installs an error handler forWebSocketRequestValidationError
which performs the correct handling of callingclose()
.