Skip to content

Exceptions

An exception is a named struct with native Elixir exception behavior. Construct, update and match it as a value. Construction does not raise.

Use an exception when an error needs Elixir’s exception interface. For failures handled entirely as data, a regular struct or variant can also be a Result payload.

A module owns one exception. Its fields can have defaults, just like a struct:

mod exceptions.validation_error
@moduledoc """
An exception is a named struct with native Elixir exception behavior.
Construct, update and match it as a value. Construction does not raise.
"""
exception ValidationError {
message: String = "Invalid value",
field: String
}
pub fn new(field: String) -> ValidationError {
%ValidationError{field: field}
}
pub fn require_name(name: String) -> Result<String, ValidationError> {
if name == "" {
Error(%ValidationError{field: "name", message: "Name must not be empty"})
} else {
Ok(name)
}
}
pub fn failed_field(result: Result<String, ValidationError>) -> Option<String> {
case result {
Ok(_) -> None
Error(%ValidationError{field: field}) -> Some(field)
}
}

require_name("") returns an Error carrying the field and message. The caller can match that value without a rescue block. Constructing or returning it does not raise or capture a stack trace.

new("name") uses the default message. Field access and updates work as they do for structs: %{error | message: "Name must not be empty"} produces a new value. Exceptions cannot have type parameters.

Gale emits Exceptions.ValidationError with defexception. The native module name comes from the enclosing Gale module:

error = Exceptions.ValidationError.new("name")
Exception.message(error) # "Invalid value"
is_exception(error) # true

Provide a message: String field or a public message(error: ValidationError) -> String function. A custom function takes precedence over the field when Elixir calls Exception.message.

An extern raises declaration catches the listed native exceptions and returns Error values. A successful native return becomes Ok.

mod exceptions.parsing
@moduledoc """
An `extern raises` declaration catches the listed native exceptions and returns
`Error` values. A successful native return becomes `Ok`.
"""
pub extern exception "ArgumentError" ArgumentError {
message: String
}
extern raises "String.to_integer" integer_native(value: String) -> Result<Integer, ArgumentError>
pub fn integer(value: String) -> Result<Integer, ArgumentError> {
integer_native(value)
}

integer("42") returns Ok(42). integer("no") returns Error with the native ArgumentError value, whose message field is available to the caller.

extern exception describes an existing Elixir type; it does not define a new exception module. Only the exceptions listed in an extern raises signature are caught. Other exceptions and process exits retain their native behavior. See externs for other foreign declarations.