Skip to content

Instantly share code, notes, and snippets.

@josefrichter
Created December 13, 2021 11:10
Show Gist options
  • Save josefrichter/127f8363fd4507b400fd54ffde5dfac9 to your computer and use it in GitHub Desktop.
Save josefrichter/127f8363fd4507b400fd54ffde5dfac9 to your computer and use it in GitHub Desktop.
Genserver: How to return errors from cast?
defmodule Stack do
use GenServer
# Client
def start_link(default) when is_list(default) do
GenServer.start_link(__MODULE__, default)
end
def push(pid, element) do
GenServer.cast(pid, {:push, element})
end
def pop(pid) do
GenServer.call(pid, :pop)
end
# Server (callbacks)
@impl true
def init(stack) do
{:ok, stack}
end
@impl true
def handle_call(:pop, _from, [head | tail]) do
{:reply, head, tail}
end
@impl true
def handle_cast({:push, element}, state) do
if length(element) > 3 do
raise "stack full"
else
{:noreply, [element | state]}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment