Created
December 13, 2021 11:10
-
-
Save josefrichter/127f8363fd4507b400fd54ffde5dfac9 to your computer and use it in GitHub Desktop.
Genserver: How to return errors from cast?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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