Dealing with Errors
import IEx.Helpers
Let it crash
# spawn_link fn -> 1 / 0 end
# spawn_link fn -> raise "booM!" end
i + 1
Errors as Data
{:error, "some message"}
:error
# Integer.parse("42 apples") # {42, " apples"}
Integer.parse("I have 42 apples")
Errors as Exceptions
# String.to_integer("42") # 42
String.to_integer("")
How to cause them
1 / 0
hd []
List.first([])
raise "Oops..."
raise RuntimeError, "bad things, man..."
raise ArgumentError, "bad things, man..."
ArgumentError.__struct__
# or
%ArgumentError{}
How to customize them
defmodule MyException do
defexception message: "Whoa... that went poorly..."
end
raise MyException
raise MyException, "mistakes were made..."
How to eal with them
try do
raise "booM!"
rescue
e -> RuntimeException
{:error, e.message}
end
try do
cond do
Enum.random([1, 2]) == 1 -> {:ok, 1}
true -> raise "boom"
end
rescue
e -> RuntimeException
{:error, e.message}
end
try do
cond do
Enum.random([1, 2]) == 1 -> {:ok, 1}
true -> raise "boom"
end
rescue
e -> RuntimeException
{:error, e.message}
after
# clean up code here
IO.puts "cleaning up :)"
end