websocketelixircowboy

Elixir: return custom error on websocket init


Hello I'm working on websocket server which should also authenticate user by user and user token. But I also need to differentiate the reason why websocket has been disconnected on client and reconnect if the error was unexpected.

defmodule MyApp.SocketHandler do
  def init(request, _state) do
    ...
    case UserAuthenticator.auth(user_id, user_token)
      {:ok, :successful_authentication} -> 
        state = %{...}
        {:cowboy_websocket, request, state}
      _ ->
        <how to implement the custom error code here and terminate connection properly>
    end
  end
end

So the question is how to implement the proper termination of websocket connection and should I do that in init function?


Solution

  • The answer was to carefully read the documentation. Well the answer is: init function is the wrong place to handle authentication. It should be done in websocket_init.

    Explanation can be found here: https://ninenines.eu/docs/en/cowboy/2.6/guide/ws_handlers/

    so to properly close the connection we can do:

    def websocket_init(state) do
      {:reply, {:close, 1000, "reason"}, state}
    end