In Elixir, when something goes wrong at runtime—like a crash or an exception—you often want to understand where it happened and why. That’s where __STACKTRACE__/0 comes in.

What is __STACKTRACE__/0?

The __STACKTRACE__/0 special form gives you access to the current stack trace inside a rescue or catch block. It's useful for debugging and error reporting, especially when you want to log or analyze where exactly the error occurred.

This macro returns the current stack trace as a list of tuples, with each tuple representing a call frame: {module, function, arity_or_args, location}.

Example Use Case

Let’s say you have a function that might raise an error, and you want to log the stack trace:

defmodule MyApp.SafeRunner do
  def run(fun) when is_function(fun, 0) do
    try do
      fun.()
    rescue
      exception ->
        IO.puts("Error: #{inspect(exception)}")
        IO.puts("Stacktrace:")
        IO.inspect(__STACKTRACE__)
        {:error, exception}
    end
  end
end

Sample Output

MyApp.SafeRunner.run(fn -> 1 / 0 end)

Output:

Error: %ArithmeticError{message: "bad argument in arithmetic expression"}
Stacktrace:
[
  {MyApp.SafeRunner, :"-run/1-fun-0-", 0, [file: "lib/my_app/safe_runner.ex", line: 3]},
  ...
]

Important Notes

  • __STACKTRACE__/0 only works inside rescue and catch blocks.
  • It is not available in after blocks or regular function bodies.
  • It's especially helpful when integrating with error-reporting tools like Sentry or Honeybadger.

Conclusion

When you need insight into runtime errors in Elixir, __STACKTRACE__/0 is a powerful tool to have in your toolbox. It gives you precise visibility into the function call path that led to the failure, making debugging and observability much easier.