Debugging Elixir Dependencies
I’m fairly new to Elixir, and still learning the ins and outs of the language and related frameworks, but a way to contribute back to the community is to share things I learn. So, I’m sharing something I learnt about Elixir recently.
I come from a background of Java and Ruby and there are various techniques on how to debug, including support in IDEs that let me debug dependencies quite nicely (like Intellij and RubyMine by JetBrains), where I can dive inside a dependency add a breakpoint on the line I want to debug.
What about Elixir?
The other day I came across an exception in Elixir which was raised from a Library. I wasn’t using an IDE in this instance (just Sublime Text, I’m still deciding what editor/IDE I want to use) so I was wondering what tools or techniques were available for debugging dependencies that was not reliant on an editor/IDE.
There must be something out there!
Coming from Ruby, there is a gem called Better Errors (that can be used for Rack Apps like Rails) which prints the stacktrace and also provides a handle on the variables at that point in time (in the browser!)
A readable interface and a convenient way to check variables you’re interested in (for more info, check out this RailsCast). Also supports checking the variables in the view.
In Elixir, there is something similar for phoenix apps by default (side note: Plug.Debugger — stumbled across this old issue), however this didn’t have the ability to check values of variables when errors occurred, so I wondered what other techniques I could use.
Debugging Elixir code
Within Elixir, there a couple of ways to debug, for instance
(1) Debugging statements using IO.puts or IO.inspect
IO.inspect(my_variable)
(2) Using Elixir’s debugger
$ iex -S mix
iex> :debugger.start()
iex> :int.ni(ModuleName)
iex> :int.break(ModuleName, line_number) # e.g. :int.break(:Math, 3)
(3) Adding pry
(Similar to Ruby’s pry)
require IExIEx.pry # add this where you want to debug
Debugging Dependencies
For a dependency there are a couple of extra steps.
Firstly, notice that dependencies are downloaded to the deps directory of the app
myapp/deps/name-of-dependency
Step 1: From here, you can locate where you want to debug (and use options above e.g. IO.puts)
Step 2: Then you need to compile the dependencies
mix deps.compile
Step 3: Run the app and start debugging
Step 4: Clean up — once you’re done, and you want to re-download the dependency
mix deps.clean name-of-dependency
mix deps.get
Happy debugging!