jswny

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

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

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

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.

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement