Chapter 10. Handling Errors

Étude 10-1: try and rescue

Update the stats module that you wrote in Étude 7-3 so that it will catch errors in the minimum/1, maximum/1, mean/1 and stdv/1 functions.

Here is some sample output.

iex(1)> c("stats.ex")
[Stats]
iex(2)> Stats.minimum([])
%MatchError{term: []}
iex(3)> Stats.mean([])
%ArithmeticError{}
iex(4)> Stats.mean([:one, :two])
%ArithmeticError{}
iex(5)> Stats.stdv([1])
%ArithmeticError{}

See a suggested solution in Appendix A.

Étude 10-2: Logging Errors

Write a module named Bank that contains a function account/1. The function takes a numeric balance, which gives the current balance in the account in imaginary dollars.

The function will repeatedly ask for a transaction (deposit, withdraw, balance inquiry, or quit). If a deposit or withdrawal, it asks for the amount to deposit or withdraw, and then does that transaction. If a deposit is more than $10,000, the deposit may be subject to hold.

Provide output to the customer, and also use error_logger to write to a log file (which, in this case, will go to your terminal). Choose any form of input prompts and feedback and logging messages that you desire. Handle the following situtations:

  • Deposits and withdrawals cannot be negative numbers (error)
  • Deposits of $10,000 or more might be subject to hold (warning)
  • All other transactions are successful (informational)

Use get_number/1 from Étude 5-2 to allow either integer or float input; you may want to modify it to take the entire prompt as its argument. ...

Get Études for Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.