2017-07-27 5 views
1

私はmessage = %{"to" => "testuser", "value" => "asdads"}のマップを持っています。私はこれがあなたのマップのキーは文字列ではなく、原子でコンソールエラーメッセージフェニックスエリキシラーの枠組みの中でマップ内の値にアクセスするにはどうすればいいですか

[error] GenServer #PID<0.395.0> terminating 
** (KeyError) key :to not found in: %{"to" => "testuser", "value" => "aadadadad"} 
    (phoenix_chat) web/channels/room_channel.ex:31: PhoenixChat.RoomChannel.handle_in/3 
    (phoenix) lib/phoenix/channel/server.ex:225: anonymous fn/4 in 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.Message{event: "message:new", payload: %{"to" => "testuser", "value" => "aadadadad"}, ref: "4", topic: "room:Pamidu"} 
State: %Phoenix.Socket{assigns: %{user: "Pamidu"}, channel: PhoenixChat.RoomChannel, channel_pid: #PID<0.395.0>, endpoint: PhoenixChat.Endpoint, handler: PhoenixChat.UserSocket, id: nil, joined: true, pubsub_server: PhoenixChat.PubSub, ref: nil, serializer: Phoenix.Transports.WebSocketSerializer, topic: "room:Pamidu", transport: Phoenix.Transports.WebSocket, transport_name: :websocket, transport_pid: #PID<0.384.0>} 
+0

'メッセージ[ "と"]'のように行うことができますか? – Dogbert

+0

また、 'message'ではなく' massage'という宣言もあります –

答えて

4

ある

これまで「と」このマップ内のキー

message.to 
message[:to] 
Map.fetch!(message, to) 

何も仕事の値にアクセスする必要があります。投稿した3つのコードスニペットはすべて、(アトム)のキーにアクセスし、"to"(ストリング)にはアクセスしません。

message["to"]を使用して値にアクセスできます。値が存在しない場合にエラーを発生させたい場合は、Map.fetch!(message, "to")を実行することもできます。

0

あなたは以下

case Map.fetch(message,"to") do 
    {:ok, value} -> IO.inspect value;   #Success 
    :error  -> IO.inspect "Key Not found" #Error 
end 
関連する問題