Kernel.defexception

You're seeing just the macro defexception, go back to Kernel module for more information.
Link to this macro

defexception(fields)

View Source (macro)

Defines an exception.

Exceptions are structs backed by a module that implements the Exception behaviour. The Exception behaviour requires two functions to be implemented:

  • exception/1 - receives the arguments given to raise/2 and returns the exception struct. The default implementation accepts either a set of keyword arguments that is merged into the struct or a string to be used as the exception's message.

  • message/1 - receives the exception struct and must return its message. Most commonly exceptions have a message field which by default is accessed by this function. However, if an exception does not have a message field, this function must be explicitly implemented.

Since exceptions are structs, the API supported by defstruct/1 is also available in defexception/1.

Raising exceptions

The most common way to raise an exception is via raise/2:

defmodule MyAppError do
  defexception [:message]
end

value = [:hello]

raise MyAppError,
  message: "did not get what was expected, got: #{inspect(value)}"

In many cases it is more convenient to pass the expected value to raise/2 and generate the message in the Exception.exception/1 callback:

defmodule MyAppError do
  defexception [:message]

  @impl true
  def exception(value) do
    msg = "did not get what was expected, got: #{inspect(value)}"
    %MyAppError{message: msg}
  end
end

raise MyAppError, value

The example above shows the preferred strategy for customizing exception messages.