{_, value} = Redix.command(:redix, ["GET", socket.assigns.user])
如果Redis数据库中没有可用的记录,则此命令失败
这是控制台中的错误显示 [
[error] GenServer #PID<0.461.0> terminating
** (FunctionClauseError) no function clause matching in PhoenixChat.RoomChannel.handle_info/2
(phoenix_chat) web/channels/room_channel.ex:14: PhoenixChat.RoomChannel.handle_info(%Phoenix.Socket.Broadcast{event: "message:new", payload: %{body: %{"to" => "rusiru", "value" => "hi bro "}, timestamp: 1501498879699, user: "abc"}, topic: "room:rusiru"}, %Phoenix.Socket{assigns: %{user: "abc"}, channel: PhoenixChat.RoomChannel, channel_pid: #PID<0.461.0>, endpoint: PhoenixChat.Endpoint, handler: PhoenixChat.UserSocket, id: nil, joined: true, pubsub_server: PhoenixChat.PubSub, ref: nil, serializer: Phoenix.Transports.WebSocketSerializer, topic: "room:abc", transport: Phoenix.Transports.WebSocket, transport_name: :websocket, transport_pid: #PID<0.421.0>})
(phoenix) lib/phoenix/channel/server.ex:239: Phoenix.Channel.Server.handle_info/2
(stdlib) gen_server.erl:601: :gen_server.try_dispatch/4
(stdlib) gen_server.erl:667: :gen_server.handle_msg/5
(stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Last message: %Phoenix.Socket.Broadcast{event: "message:new", payload: %{body: %{"to" => "rusiru", "value" => "hi bro "}, timestamp: 1501498879699, user: "abc"}, topic: "room:rusiru"}
State: %Phoenix.Socket{assigns: %{user: "abc"}, channel: PhoenixChat.RoomChannel, channel_pid: #PID<0.461.0>, endpoint: PhoenixChat.Endpoint, handler: PhoenixChat.UserSocket, id: nil, joined: true, pubsub_server: PhoenixChat.PubSub, ref: nil, serializer: Phoenix.Transports.WebSocketSerializer, topic: "room:abc", transport: Phoenix.Transports.WebSocket, transport_name: :websocket, transport_pid: #PID<0.421.0>}
[info] JOIN room:abc to PhoenixChat.RoomChannel
Transport: Phoenix.Transports.WebSocket
Parameters: %{}
[info] Replied room:abc :ok
这是room_channel.ex
def handle_info(:after_join, socket) do
{_, value} = Redix.command(:redix, ["GET", socket.assigns.user])
Presence.track(socket, socket.assigns.user, %{
online_at: :os.system_time(:millisecond),
status: value
})
push socket, "presence_state", Presence.list(socket)
{:noreply, socket}
end
如何解决此问题?
答案 0 :(得分:2)
如果密钥不存在,GET
命令将不会返回错误。它将返回{:ok, nil}
代替:
iex(1)> {:ok, conn} = Redix.start_link
{:ok, #PID<0.159.0>}
iex(2)> Redix.command(conn, ["GET", "key-that-doesnt-exist"])
{:ok, nil}
因此,您的模式匹配成功,但返回的值为nil
,您稍后会将其传递给String.trim/1
,这会引发您正在获取的错误。
你可以像这样处理不存在的密钥:
case Redix.command(:redix, ["GET", socket.assigns.user]) do
{:ok, nil} -> # key doesn't exist
{:ok, value} -> # key exists, value is in `value`
{:error, error} -> # some other error
end