我跟随此Tutorial之后第一次玩Elixir
和Phoenix Framework
..
我有一个简单的客户端/服务器应用程序。
聊天/ LIB / chat_web / room_channel.ex:
defmodule ChatWeb.RoomChannel do
use Phoenix.Channel
def join("room:lobby", _message, socket) do
{:ok, socket}
end
def join("room:" <> _private_room_id, _params, _socket) do
{:error, %{reason: "unauthorized"}}
end
def handle_in("new_msg", %{"body" => body}, socket) do
broadcast! socket, "new_msg", %{body: body}
{:noreply, socket}
end
end
我想阻止空的传入消息(body
为空字符串)
def handle_in("new_msg", %{"body" => body}, socket) do
# I guess the code should be here..
broadcast! socket, "new_msg", %{body: body}
{:noreply, socket}
end
我该怎么做?
答案 0 :(得分:4)
我想阻止空的传入消息(正文为空字符串)
您可以为此添加一个保护条款。 when body != ""
或when byte_size(body) > 0
def handle_in("new_msg", %{"body" => body}, socket) when body != "" do
...
end
现在,只有当body
不是""
时,此功能才会匹配。
如果你还想处理空体情况,你可以添加这样的两个子句(不再需要guard子句,因为如果body为空,第二个子句永远不会匹配):
def handle_in("new_msg", %{"body" => ""}, socket) do
# broadcast error here
end
def handle_in("new_msg", %{"body" => body}, socket) do
# broadcast normal here
end
答案 1 :(得分:2)
你可以使用@Dogbert提出的答案,但要100%确定字符串不为空,你可以使用在助手私有函数中包装hello 3
或者只包含broadcast!
或{{ 1}}(否定if)表达式。
if
如果您想要返回错误消息,请尝试使用更复杂的内容,例如:
unless