Handle phoenix socket.connect() error

I’m using phoenix 1.3.2

I have a socket that checks for user authentication at connection time:

def Socket do
   use Phoenix.Socket

  def connect(params, socket) do
     case check_authentication_params(params) do 
       {:ok, authed_socket} -> {:ok, authed_socket}
       _ -> :error 
    end
  end
   
end

I connect in a browser with the phoenix npm package:

import { Socket } from 'phoenix';

let webSocket = new Socket(`....`);

webSocket.onError(error => {
   // Handle error
});

webSocket.connect()

My problem is that, on the client side, in the webSocke.onError handler, the error event seems to be the same when:

  • the connect succeeds, but later the connection is dropped (momentarily, for example, when my server restarts)
  • the connection is done with wrong params, so the connect function returns :error. I have log line that says:
WebSocket connection to '....t?vsn=2.0.0' failed: Error during WebSocket handshake: Unexpected response code: 403

But I cannot make the difference in the code.

What I want to do is to forcefully disconnect the websocket (to avoid repeated reconnection attempt) when I know the client does not have the proper credentials.

If I always use webSocket.disconnect in the error handler, then, as I understand it, I loose automatic reconnection in case of a network hicup.

Is there a way around that ?

4 Likes