LoginSignup
3
4

More than 5 years have passed since last update.

Elixirでcall stackを表示する

Last updated at Posted at 2016-01-10

スマートではないですが、以下のようにして表示できます。

#!/usr/bin/env elixir
defmodule Bar do
  def bar do
    try do raise "oops" rescue _ -> IO.inspect System.stacktrace end
  end
end

defmodule Foo do
  def foo do
    Bar.bar
  end
end

Foo.foo
[{Bar, :bar, 0, [file: 'test.exs', line: 4]},
 {:elixir_compiler, :dispatch_loaded, 6,
  [file: 'src/elixir_compiler.erl', line: 126]},
 {:elixir_lexical, :run, 3, [file: 'src/elixir_lexical.erl', line: 16]},
 {:elixir_compiler, :quoted, 3, [file: 'src/elixir_compiler.erl', line: 30]},
 {Code, :require_file, 2, [file: 'lib/code.ex', line: 363]},
 {Mix.Tasks.Run, :run, 1, [file: 'lib/mix/tasks/run.ex', line: 68]},
 {Mix.CLI, :run_task, 2, [file: 'lib/mix/cli.ex', line: 58]},
 {:elixir_compiler, :dispatch_loaded, 6,
  [file: 'src/elixir_compiler.erl', line: 126]}]

Exception.formatを使うと、もうちょいきれいになります。

try do raise "oops" rescue e -> IO.puts Exception.format(:error, e) end

#** (RuntimeError) oops
#    test.exs:4: Bar.bar/0
#    (elixir) src/elixir_compiler.erl:126: :elixir_compiler.dispatch_loaded/6
#    (elixir) src/elixir_lexical.erl:16: :elixir_lexical.run/3
#    (elixir) src/elixir_compiler.erl:30: :elixir_compiler.quoted/3
#    (elixir) lib/code.ex:363: Code.require_file/2
#    (mix) lib/mix/tasks/run.ex:68: Mix.Tasks.Run.run/1
#    (mix) lib/mix/cli.ex:58: Mix.CLI.run_task/2
#    (elixir) src/elixir_compiler.erl:126: :elixir_compiler.dispatch_loaded/6

うーん、しかしほんとにこれしか方法ないんだろうか…

あとFoo.fooが表示されないのも謎。

  def foo do
    Bar.bar
    IO.puts 100
  end

としたら、Foo.fooも表示された。

** (RuntimeError) oops
    test.exs:4: Bar.bar/0
    test.exs:10: Foo.foo/0
    (elixir) src/elixir_compiler.erl:126: :elixir_compiler.dispatch_loaded/6
    (elixir) src/elixir_lexical.erl:16: :elixir_lexical.run/3
    (elixir) src/elixir_compiler.erl:30: :elixir_compiler.quoted/3
    (elixir) lib/code.ex:363: Code.require_file/2
    (mix) lib/mix/tasks/run.ex:68: Mix.Tasks.Run.run/1
    (mix) lib/mix/cli.ex:58: Mix.CLI.run_task/2

最適化されてる?

あと、Exceptionのリファレンスで

Note that stacktraces in Elixir are updated on throw, errors and exits. For example, at any given moment, System.stacktrace/0 will return the stacktrace for the last throw/error/exit that occurred in the current process.

とあるんですが、これ「実用上問題ないからOK!」ってことなんですかね…

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4