[Proposal] GenServer response with exception control flow

50 views
Skip to first unread message

Elias Arruda

unread,
Apr 25, 2022, 4:52:27 PM4/25/22
to elixir-lang-core
It would be cool to have the possibility to be able to use exceptions as control flow for successful GenServer responses

I'm sure there is the opinion that this is anti-pattern, but having the possibility could really simplify some handler functions scenarios where you need to validate a lot of different entries

Having guard clauses to validate things could help

```
if a > b, do: reply! :some_error, state
```

In practice it would be something like this:

------

# We could have a GenResponse module that acts as a Exception
```
defmodule GenResponse do
  defexception [:res, :new_state, :value, :extra]
end

# All GenServer handle functions would need to have a exception wrapper in compile time, this could maybe be configured with something like:
# > use GenServer, exception_flow: true
try do
  # Could be used directly like this
  raise GenResponse, res: :noreply, new_state: :any

  # Or also like this
  noreply! :any
rescue
  # Essentially, in every handle function something like this would be under the hood
  res in GenResponse ->
    case res do
      %GenResponse{res: :noreply, new_state: state} ->
        {:noreply, state}

      %GenResponse{res: :reply, value: value, new_state: state} ->
        {:reply, value, state}
    end
end
```




Ben Wilson

unread,
Apr 26, 2022, 10:50:31 AM4/26/22
to elixir-lang-core
> I'm sure there is the opinion that this is anti-pattern

Yup. Side stepping this a bit though and getting to something deeper: This does not seem like it needs to be part of the standard library. You could make a library called GenServerWithExceptions or something and put it up on hex, and see if people use it. If it's wildly successful and takes over the way people do GenServers then there could maybe be an argument for including it in the language, but given that exception driven control flow is indeed considered an anti-pattern most of the time, and that you can implement this outside the language, it seems premature to push for inclusion at this time.

Reply all
Reply to author
Forward
0 new messages