How to send error in websocket?


On a standard HTTP request, I can send back a 401 status code to ask for authentication, but it seems this is not possible on Websocket:

return json('Please authenticate yourself', status=401)

What is the alternative on that case?

Thanks :slight_smile:

You want to keep the connection and just send an error, or close the connection?

Once you have the socket open, it’s really up to you to establish the language of messages that both sides will use. I typically will create json Objects so I can pass nested data, or errors.

Or, are you looking to add an authentication to your websocket?

It is in the idea of authenticating yes, so I believe the connection should be stopped if the authentication is invalid.

Here’s what I came to so far:

    if not token:
        return await ws.close(code=1011, reason=json.dumps({'code': 401, 'error': 'Please authenticate yourself.'}))

The reason for the 1011 code is from the RFC:

 1011 indicates that a server is terminating the connection because
 it encountered an unexpected condition that prevented it from
 fulfilling the request.

In the above scenario, the connection is successful, and when I call the close, the connection is closed. There is no error thrown.

I (wrongly) thought that sending another code (1011 in that case) would trigger an error on the websocket client. Instead, it just closes the connection with the given code.

I don’t know if there is a specific structure to implement authentication, but I think the above implementation is wrong. Currently, it does the following :

  1. Connects
  2. Tries to send the pending data
  3. Gets a close event from the server with a code 1011

Ideally, and instead, what would be good is :

  1. Connects
  2. Gets an error and the connection is terminated

That means, in the function processing the incoming new connection, it would be good to have a way to say when the connection is indeed open, rather than rely on Sanic for that (if that is possible in term of protocol).