【问题标题】:Handling Errors - Elixir处理错误 - Elixir
【发布时间】:2020-04-24 20:19:54
【问题描述】:

我有一个这样的简单函数:

  def currencyConverter({ from, to, amount }) when is_float(amount) do
    result = exchangeConversion({ from, to, amount })
    exchangeResult = resultParser(result)
    exchangeResult
  end

我想保证 from 和 to 是字符串,而金额是浮点数,如果不是,则显示发送自定义错误消息而不是 erlang 错误 最好的方法是什么?

【问题讨论】:

标签: exception error-handling elixir


【解决方案1】:

您可以创建两个具有相同名称和数量的函数,一个带守卫,一个不带守卫

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

【讨论】:

  • 我认为你应该使用is_binary 而不是is_bitstring
  • 不错!但是使用这个,我可以知道哪个输入对自定义消息无效吗?
  • @zwippie 取决于用例。 'foo' 是二进制但不是位串。 “foo”是二进制和位串。
  • @RafaelPolonio 刚刚用你的答案编辑了帖子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 2015-02-14
相关资源
最近更新 更多