The Exception Behaviour defines how errors
are raised and displayed.
It includes two optional callbacks:
message/1
transforms the error-struct into a readable message.exception/1
creates the message from the 2nd argument in raise/2
allowing the message to be modified.Defined errors:
:message
field.raise/1
and raise/2
to raise the intended errorTo define an exception from an error module, use the defexception
macro:
# Defines a minimal error, with the name `MyError`
defmodule MyError do
defexception message: "error"
end
# Defines an error with a customized exception/1 function
defmodule MyCustomizedError do
defexception message: "custom error"
@impl true
def exception(value) do
case value do
[] ->
%MyCustomizedError{}
_ ->
%MyCustomizedError{message: "Alert: " <> value}
end
end
end
Defined errors may be used like a built in error using either raise/1
or raise/2
:
raise MyError
# => ** (MyError) error
raise MyError, "an error occurred"
# => ** (MyError) an error occurred
raise MyCustomizedError
# => ** (MyCustomizedError) "custom error"
raise MyCustomizedError, "a very bad error occurred"
# => ** (MyCustomizedError) Alert: a very bad error occurred