jswny
Advice on how to avoid Go-like error handling patterns in Elixir?
Hi all! I’m fairly new to Elixir. I’ve read a book or two, but am just getting into using the language in practice. I recently needed to write a simple function to update a key in a JSON file. However, I found myself running into a lot of repetitive Go-esque error checking. I’m new to functional programming and I was wondering if there is a more idomatic way to handle this type of situation, or just a way to improve it. I’m not a fan of this style as it is because it’s a huge block of ever-indenting lines like old JavaScript. Here is a slimmed down example I came up with:
defmodule Test do
@doc """
Inserts the given JSON into the `data` field of `file`.
"""
def insert(file, data) do
# Read the contents of the file
case File.read(file) do
{:ok, content} ->
# Decode the file to JSON
case Poison.decode(content) do
{:ok, decoded_content} ->
# Encode the given data to JSON
case Poison.encode(data) do
{:ok, encoded_data} ->
# Prepare the updated data for insertion
final_data = Map.update(decoded_content, "data", encoded_data, fn _ -> encoded_data end)
# Encode the updated data
case Poison.encode(final_data) do
{:ok, encoded_final_data} ->
# Write the updated data to the file
case File.write(file, encoded_final_data) do
:ok -> IO.puts "Successfully updated file!"
{:error, reason} -> IO.puts "Could not write to file because #{reason}!"
end
{:error, {:invalid, reason}} -> IO.puts "Could not encode updated JSON because #{reason}!"
end
{:error, {:invalid, reason}} -> IO.puts "Could not encode given JSON because #{reason}!"
end
{:error, :invalid} -> IO.puts "Could not parse file to JSON!"
{:error, :invalid, reason} -> IO.puts "Could not parse file to JSON because #{reason}!"
end
{:error, reason} -> IO.puts "Could not read file because #{reason}!"
end
end
end
Keep in mind, I just wrote this as a quick example. It’s not my actual code nor is it perfect code. I’m just trying to demonstrate the error handling pattern I’m Talking about. Thanks in advance!
Most Liked
peerreynders
All the other advice is good - but at the most basic level keep your functions small, tiny even - e.g.:
defmodule Test do
defp reportOnFileWrite(:ok),
do: IO.puts "Successfully updated file!"
defp reportOnFileWrite({:error, reason}),
do: IO.puts "Could not write to file because #{reason}!"
defp writeEncodedFinalData({:ok, encoded_final_data}, file),
do: reportOnFileWrite (File.write file, encoded_final_data)
defp writeEncodedFinalData({:error, {:invalid, reason}}, _),
do: IO.puts "Could not encode updated JSON because #{reason}!"
defp writeEncodedData({:ok, encoded_data}, file, decoded_content) do
# Prepare the updated data for insertion
final_data = Map.update(decoded_content, "data", encoded_data, fn _ -> encoded_data end)
# Encode the updated data
writeEncodedFinalData (Poison.encode final_data), file
end
defp writeEncodedData({:error, {:invalid, reason}}, _, _) do
IO.puts "Could not encode given JSON because #{reason}!"
end
defp writeDecodedContent({:ok, decoded_content}, file, data),
do: writeEncodedData (Poison.encode data), file, decoded_content
defp writeDecodedContent({:error, :invalid}, _, _),
do: IO.puts "Could not parse file to JSON!"
defp writeDecodedContent({:error, :invalid, reason}, _, _),
do: IO.puts "Could not parse file to JSON because #{reason}!"
defp rewrite({:ok, content}, file, data),
do: writeDecodedContent (Poison.decode content), file, data
defp rewrite({:error, reason}, _, _),
do: IO.puts "Could not read file because #{reason}!"
@doc """
Inserts the given JSON into the `data` field of `file`.
"""
def insert(file, data) do
# Read the contents of the file
rewrite (File.read file), file, data
end
end
This is essentially just a starting point for all the other pieces of advice you are getting. Once things are broken down in this manner it becomes much easier to factor things out.
Never forget that everything is an expression (forget about statements).
sergio
I got this tip courtesy of the Pragmatic Studio Elixir course.
Instead of nesting case statements, use function pattern matching to handle conditional branches.
File.read(file)
|> handle_file
def handle_file({:ok, content}) do
Poison.decode(content)
|> handle_encode
end
def handle_file({:error, reason}) do
# Something someting
end
And so on.
dom
You can use the with/else syntax in some cases, pipelining through several functions that match on their input and return it unmodified if it’s an error is also an option.
More generally though, it’s better not to handle an error case explicitly unless it’s expected to happen and you need to send a helpful message back to the caller/user. A supervisor crash log is a lot more useful for debugging than a vague log message like “could not read file” etc. See Erlang and code style: Musings on mostly defensive programming styles.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








