0
我嘗試預處理websocket傳入消息。在lobby_channel.ex
文件我有:「Elixir + phoenix」過濾websocket消息
defmodule Chatroom.LobbyChannel do
use Phoenix.Channel
def join("room:lobby", _payload, socket) do
{:ok, socket}
end
def join("room:" <> _private_room_id, _params, _socket) do
{:error, %{reason: "unauthorized"}}
end
def handle_in("new_move", payload, socket) do
changeset = Chatroom.Move.changeset(%Chatroom.Move{}, payload)
if changeset.valid? do
broadcast! socket, "new_move", payload
{:noreply, socket}
else
IO.puts "-----" <> changeset.errors[:message]
push socket, "error", %{msg: "Invalid move"}
{:noreply, socket}
end
end
#intercept ["new_move"]
#def handle_out("new_move", payload, socket) do
# IO.puts payload["name"] <> "=======" <> payload["message"]
# push socket, "new_move", payload
# {:noreply, socket}
#end
end
模型文件包含驗證功能:
...
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:name, :message])
|> validate_required([:name, :message])
|> validate_length(:name, min: 1)
|> validate_length(:message, is: 2)
|> is_move_allowed(params)
end
defp is_move_allowed(changeset, params) do
IO.puts "--zz---" <> params["message"]
if params["message"] == "00" do
IO.puts "--yy---" <> params["message"]
add_error(changeset, params["message"], "'message' cannot be '00'")
else
IO.puts "--xx---" <> params["message"]
[]
end
end
...
..the最後一個是我的自定義驗證功能,我不能讓它的工作沒有錯誤。輸出我得到:
--zz---00
--yy---00
[error] GenServer #PID<0.445.0> terminating
** (ArgumentError) argument error
:erlang.byte_size(nil)
(chatroom) web/channels/lobby_channel.ex:18: Chatroom.LobbyChannel.handle_in/3
(phoenix) lib/phoenix/channel/server.ex:226: 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: "new_move", payload: %{"message" => "00", "name" => "a"}, ref: "2", to
pic: "room:lobby"}
State: %Phoenix.Socket{assigns: %{}, channel: Chatroom.LobbyChannel, channel_pid: #PID<0.445.0>, endpoint: Chatroom
.Endpoint, handler: Chatroom.UserSocket, id: nil, joined: true, pubsub_server: Chatroom.PubSub, ref: nil, serialize
r: Phoenix.Transports.WebSocketSerializer, topic: "room:lobby", transport: Phoenix.Transports.WebSocket, transport_
name: :websocket, transport_pid: #PID<0.439.0>}
據我瞭解,事情正在向邏輯上正確的方式,消息中包含正確的數據,但我怎麼能解決這個錯誤嗎?我錯過了什麼?
嘗試將其他中的'[]'更改爲'changeset'。 – Dogbert
@Dogbert,同樣的錯誤。對於「00」消息和所有其他人 – Alexey
你可以發佈「web/channels/lobby_channel.ex」的完整內容嗎? – Dogbert