Exception 处理错误-长生不老药
我有一个简单的函数,如下所示:Exception 处理错误-长生不老药,exception,error-handling,elixir,Exception,Error Handling,Elixir,我有一个简单的函数,如下所示: def currencyConverter({ from, to, amount }) when is_float(amount) do result = exchangeConversion({ from, to, amount }) exchangeResult = resultParser(result) exchangeResult end 我想保证from和to是字符串,amount是float,如果不是,display
def currencyConverter({ from, to, amount }) when is_float(amount) do
result = exchangeConversion({ from, to, amount })
exchangeResult = resultParser(result)
exchangeResult
end
我想保证from和to是字符串,amount是float,如果不是,display将发送一条定制错误消息,而不是erlang error
最好的方法是什么?您可以创建两个名称和算术相同的函数,一个带保护,另一个不带保护
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函数基于此帖子:)你可以使用
is_float(amount)
等-参见旁注:永远不要使用float
类型表示货币。我认为你应该使用is_binary
而不是is_bitstring
。很好!但是使用这个,我可以知道哪个输入对自定义消息无效吗?@zwippie取决于用例“foo”是二进制的,但不是位字符串。“foo”是二进制和位字符串。@RafaelPolonio刚刚用你的答案编辑了这篇文章