chanon

chanon

Phoenix Websocket Error/Exception Handling

I am using something like this to to handle Websocket requests:

  def handle_in("new_msg", data, socket) do

    # do something with data that might result in exceptions/exits/errors raised

    {:reply, {:ok, output}, socket}
  end

And in JavaScript side, something like this

 channel.push("new_msg", data, 10000)
    .receive("ok", (output) => console.log("created message", output) )
    .receive("error", (reasons) => console.log("create failed", reasons) )
    .receive("timeout", () => console.log("Networking issue...") )

What happens is, when an exception is raised it seems the whole channel process (?) goes down, and the client which is waiting for a response gets no response and just times out.

What I would like instead is to be able to return an error immediately with maybe “unexpected error” reason kind of like a http 500 error.

I don’t want to leave the client hanging and it isn’t a “Networking issue” so timeout isn’t appropriate result.

After some trial and error, I now have the following, which seems to work nicely:

  def handle_in("new_msg", data, socket) do

    try do
        # do something with data that might result in exceptions/exits/errors raised
        {:reply, {:ok, output}, socket}
    catch
        :exit, error ->
            Logger.error(Exception.format_exit(reason))
            {:reply, {:error, %{reason: "Unexpected Error"}}, socket}
    end
  end

But I am a bit unsure, as

  • I think for http requests Phoenix handles this and automatically responds with 500 code? But for websocket requests I have to handle this myself?
  • And also the Elixir tutorial seems to say that you wouldn’t normally need to use try/catch
  • And would I also need a rescue?

EDIT: I am now doing it like this as all my messages need replies:

 # try catch here
 def handle_in(event, params, socket) do
    try do
      {:reply, handle(event, params, socket), socket}
    catch
      :exit, reason ->
        Logger.info("responding with unexpected error")
        Logger.error(Exception.format_exit(reason))
        {:reply, {:error, %{reason: "Unexpected Error."}}, socket}
    end
  end

# handle each message type, no boilerplate
defp handle("new_msg", params, socket) do
  # do stuff
  {:ok, %{result: output}}
end

defp handle("another_msg", params, socket) do
  # do stuff
  {:ok, %{result: output}}
end

First Post!

lud

lud

Hello,

I have the same problem. I use promises to call into the channel from different parts of my javascrtipt code :

function ppush (channel, event, payload) {
  return new Promise((resolve, reject) => {
    console.log("ppush '%s' payload:", event, payload)
    channel.push(event, payload)
      .receive('ok', resp => {
        console.log('received ok: ', resp)
        resolve(resp)
      })
      .receive('error', resp => {
        console.log('received error: ', resp)
        reject(resp)
      })
  })
}

But I have no idea how to catch exits from the channel. It would be very useful during development process.

Of course we could handle channel.onError but you have to handle all errors, not only from the current push.

Most Liked

idi527

idi527

I think there is also channel.onError which is supposed to handle channel process dying and socket disconnecting. I’d guess socket.onError only handles the latter.

Where Next?

Popular in Questions Top

minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44265 214
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement