• Stars
    star
    599
  • Rank 74,745 (Top 2 %)
  • Language
    Elixir
  • License
    Apache License 2.0
  • Created about 9 years ago
  • Updated almost 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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.

  • Use the <- operator to match & extract a value for an :ok tuple.
  • Use the = operator as you normally would for pattern matching an untagged result.
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:

  • Exceptional input and errors are not the same thing, OK leaves raising exceptions as a way to handle errors that should never happen.
  • Calls inside try/1 are not tail recursive since the VM needs to keep the stacktrace in case an exception happens. see source.

What about other shapes of error and success?

  • Accepting any extra forms is a slippery slope, and they are not always unambiguous. If a library is not returning errors as you like it is very easy to wrap in a custom function.

    def fetch_foo(map) do
      case Map.fetch(map, :foo) do
        {:ok, foo} -> {:ok, foo}
        :error -> {:error, :no_foo}
      end
    end

What changed in version 2.0

  • OK.with was deprecated.
  • use OK.Pipe was added.
  • OK.bind was renamed OK.flat_map.

Additional External Links and Resources

More Repositories

1

raxx

Interface for HTTP webservers, frameworks and clients
Elixir
401
star
2

Ace

HTTP web server and client, supports http1 and http2
Elixir
304
star
3

elixir-on-docker

Quickly get started developing clustered Elixir applications for cloud environments.
Elixir
172
star
4

eyg-lang

Experiments in building "better" languages and tools; for some measure of better.
Gleam
151
star
5

raxx_kit

Get started with Raxx + Elixir
HTML
122
star
6

pachyderm

Virtual actors for elixir
Elixir
103
star
7

gen_browser

Transparent bi-directional communication for clients, servers and more
Elixir
68
star
8

plinth

node and browser bindings for gleam
Gleam
56
star
9

watercooler

Building a distributed chatroom with Raxx.Kit
Elixir
25
star
10

server_sent_event.ex

Push updates to Web clients over HTTP or using dedicated server-push protocol
Elixir
20
star
11

awesome-eco

Resources and Prodjects addressing human ecological impact.
12
star
12

vulcanize

Form objects to coerce user input using your value objects
Ruby
10
star
13

AllSystems

Simple Ruby usecases/interactors/service-object to encapsulate business logic
Ruby
10
star
14

typetanic

A few hygenicly namespaced domain objects.
Ruby
6
star
15

rollup-karma-jasmine-example

Calculator project that bundles es6-modules with Rollup. Tests use Jasmine and are run in the browser with Karma
JavaScript
6
star
16

me

All about me
HTML
5
star
17

ace-raxx-clustering-example

An example of how to setup a multi node web service in elixir
Elixir
5
star
18

intention.js

Pure implementation of the JavaScript fetch API exposing an analogue to the promise API.
JavaScript
5
star
19

basic_authentication

Submit and verify client credentials using the 'Basic' HTTP authentication scheme.
Elixir
5
star
20

CORS

Check Cross Origin Request Security headers.
Elixir
4
star
21

comms

Explicit message passing for improved reasoning about actor systems
Elixir
4
star
22

raxx_static

Raxx middleware for serving static content.
Elixir
4
star
23

gleamtours

Tours through various topics in Gleam.
Gleam
4
star
24

greetings-ace-elixir-example

Simple greetings application to showcase developing web services with Ace
Elixir
3
star
25

cookie.ex

Elixir
3
star
26

eex_html

Extension to Embedded Elixir (EEx), that allows content to be safely embedded into HTML.
Elixir
3
star
27

num

Because floats were never really numbers
Elixir
3
star
28

no-code

Notes on no-code programming
3
star
29

raxx_api_blueprint

Route requests based on an API Blueprint
Elixir
3
star
30

carbide.js

Minimal immutable objects in JavaScript
JavaScript
3
star
31

greetings-ace-raxx-erlang-example

Simple greetings application to showcase developing web services with Ace and Raxx in erlang
Erlang
3
star
32

gleamweekly

Gleam is so hot right now. There is so much happening in our wonderful and growing community that you wouldn't want to miss.
HTML
3
star
33

raxx.rs

How to web dev with Rust
Rust
2
star
34

git_status

Compile time status of GIT repository for source code.
Elixir
2
star
35

level

A spirit level for your device. No download required
JavaScript
2
star
36

echo-server.hs

TCP echo server written in Haskell.
Haskell
2
star
37

svg-crop

Output PNG's at a variety of size's and aspect ratios from a single SVG source.
JavaScript
2
star
38

phonegap-vector-assets

Create multiple resolution assets for phonegap applications directly from config.xml
JavaScript
2
star
39

phonegap-icon-set

An example project to generate multiple icons for phonegap
JavaScript
1
star
40

Almighty

Environment recreation and dotfile plus
Shell
1
star
41

IOC-example.js

Inversion of control architecture for JavaScript applications
JavaScript
1
star
42

eyg

Explicit concurrency for intelligible parallel programing.
Rust
1
star
43

cut-the-mustard

Checking your JS environment is up to scratch
JavaScript
1
star
44

svg_agile

SVG manipulation on with touch or mouse
JavaScript
1
star
45

phonegap-screenshot-example

Generating webview screenshots for use in app stores.
JavaScript
1
star
46

lob

Demonstrating realtime connection between web browsers. Powered by ably.io. Created by Workshop14.io
JavaScript
1
star
47

Curriculum-Vitae

Curriculum Vite for Peter Saxton
TeX
1
star
48

HammerHead

A minimal JavaScript utility to help view SVG's on webpages
JavaScript
1
star
49

bbox

Find bounding box dimensions either within or surrounding arbitrary containers
JavaScript
1
star
50

just-job

Just Job is a todo list built from the ground up using the principles of Domain Driven Design(DDD)
Ruby
1
star