Обработка ошибок - эликсир - PullRequest
0 голосов
/ 22 апреля 2020

У меня есть простая функция, подобная этой:

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

Я хочу гарантировать, что строки from и to являются строками, а сумма равна float, а если нет, дисплей отправляет сообщение об ошибке настройки вместо ошибки erlang. лучший способ сделать это?

1 Ответ

1 голос
/ 23 апреля 2020

вы можете сделать две функции с одинаковым именем и арностью, одну с защитой и одну без

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"

Если вы хотите проверить тип ввода, вам нужно создать функцию, чтобы сделать это, потому что эликсир не имеет глобального.

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 основана на этом сообщении: { ссылка })

...