我有一个类似下面这样的简单函数:
def currencyConverter({ from, to, amount }) when is_float(amount) do
result = exchangeConversion({ from, to, amount })
exchangeResult = resultParser(result)
exchangeResult
end我想保证from和to的字符串和金额都是浮点型的,如果不是这样,就显示一条自定义的错误消息,而不是erlang error。最好的方法是什么?
发布于 2020-04-23 09:33:41
您可以创建两个具有相同名称和参数的函数,一个带保护,另一个不带
def currencyConverter({from, to, amount}) when is_float(amount) and is_bitstring(to) and is_bitstring(from) do
result = exchangeConversion({ from, to, amount })
exchangeResult = resultParser(result)
exchangeResult
end
def currencyConverter(_), do: raise "Custom error msg"如果您想要检查输入类型,您将需要创建一个函数来执行此操作,因为elixir没有全局函数。
def currencyConverter({from, to, amount}) when is_float(amount) and is_bitstring(to) and is_binary(from) do
result = exchangeConversion({ from, to, amount })
exchangeResult = resultParser(result)
exchangeResult
end
def currencyConverter({from, to, amount}) do
raise """
You called currencyConverter/1 with the following invalid variable types:
'from' is type #{typeof(from)}, need to be bitstring
'to' is type #{typeof(to)}, need to be bitstring
'amount' is type #{typeof(amount)}, need to be float
"""
end
def typeof(self) do
cond do
is_float(self) -> "float"
is_number(self) -> "number"
is_atom(self) -> "atom"
is_boolean(self) -> "boolean"
is_bitstring(self)-> "bitstring"
is_binary(self) -> "binary"
is_function(self) -> "function"
is_list(self) -> "list"
is_tuple(self) -> "tuple"
true -> "ni l'un ni l'autre"
end
end(typeof/1函数基于此帖子:https://stackoverflow.com/a/40777498/10998856)
https://stackoverflow.com/questions/61374411
复制相似问题