首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >处理错误- Elixir

处理错误- Elixir
EN

Stack Overflow用户
提问于 2020-04-23 04:19:29
回答 1查看 104关注 0票数 0

我有一个类似下面这样的简单函数:

代码语言:javascript
复制
  def currencyConverter({ from, to, amount }) when is_float(amount) do
    result = exchangeConversion({ from, to, amount })
    exchangeResult = resultParser(result)
    exchangeResult
  end

我想保证from和to的字符串和金额都是浮点型的,如果不是这样,就显示一条自定义的错误消息,而不是erlang error。最好的方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-23 09:33:41

您可以创建两个具有相同名称和参数的函数,一个带保护,另一个不带

代码语言:javascript
复制
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没有全局函数。

代码语言:javascript
复制
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)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61374411

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档