Home

Awesome

OK

Elegant error/exception handling in Elixir, with result monads.

Hex pm Build Status License

Result tuples

The OK module works with result tuples by treating them as a result monad.

{:ok, value} | {:error, reason}

See Handling Errors in Elixir for a more detailed explanation.

See FAQ at end of README for a few common question.

OK.for

OK.for/1 combines several functions that may fail.

require OK

OK.for do
  user <- fetch_user(1)             # `<-` operator means func returns {:ok, user}
  cart <- fetch_cart(1)             # `<-` again, {:ok, cart}
  order = checkout(cart, user)      # `=` allows pattern matching on non-tagged funcs
  saved_order <- save_order(order)
after
  saved_order                       # Value will be wrapped if not already a result tuple
end

OK.for/1 guarantees that it's return value is also in the structure of a result tuple.

OK.try

OK.try/1 combines several functions that may fail, and handles errors.

This is useful when writing code that has it's own representation of errors. e.g. HTTP Responses.

For example when using raxx to build responses the following code will always return a response.

require OK
import Raxx

OK.try do
  user <- fetch_user(1)             # `<-` operator means func returns {:ok, user}
  cart <- fetch_cart(1)             # `<-` again, {:ok, cart}
  order = checkout(cart, user)      # `=` allows pattern matching on non-tagged funcs
  saved_order <- save_order(order)
after
  response(:created)                # Value will be returned unwrapped
rescue
  :user_not_found ->
    response(:not_found)
  :could_not_save ->
    response(:internal_server_error)
end

OK Pipe

The pipe (~>>) is equivalent to bind/flat_map. The pipe (~>) is equivalent to map.

These macros allows pipelining result tuples through multiple functions for an extremely concise happy path.

use OK.Pipe

def get_employee_data(file, name) do
  {:ok, file}
  ~>> File.read
  ~> String.upcase
end

Use ~>> for File.read because it returns a result tuple. Use ~> for String.upcase because it returns a bare value that should be wrapped in an ok tuple.

Semantic matches

OK provides macros for matching on success and failure cases. This allows for code to check if a result returned from a function was a success or failure while hiding implementation details about how that result is structured.

import OK, only: [success: 1, failure: 1]

case fetch_user(id) do
  success(user) ->
    user
  failure(:not_found) ->
    create_guest_user()
end

FAQ

Why does OK not catch raised errors?

For the main rational behind this decision see the article Errors are not exceptional

Two other reasons:

What about other shapes of error and success?

What changed in version 2.0

Additional External Links and Resources