From 0ec59319ed03130ead424a210f6088012b650565 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 18 Mar 2019 09:49:42 -0500 Subject: [PATCH] Add When Things Don't Match The With Statements as an elixir til --- README.md | 3 +- ...n-things-dont-match-the-with-statements.md | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 elixir/when-things-dont-match-the-with-statements.md diff --git a/README.md b/README.md index 8b85f86..8ea62b1 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_784 TILs and counting..._ +_785 TILs and counting..._ --- @@ -163,6 +163,7 @@ _784 TILs and counting..._ - [Updating Values In A Map](elixir/updating-values-in-a-map.md) - [Using When Clauses In A With Construct](elixir/using-when-clauses-in-a-with-construct.md) - [Virtual Fields With Ecto Schemas](elixir/virtual-fields-with-ecto-schemas.md) +- [When Things Don't Match The With Statements](elixir/when-things-dont-match-the-with-statements.md) - [Word Lists For Atoms](elixir/word-lists-for-atoms.md) ### Git diff --git a/elixir/when-things-dont-match-the-with-statements.md b/elixir/when-things-dont-match-the-with-statements.md new file mode 100644 index 0000000..4531fef --- /dev/null +++ b/elixir/when-things-dont-match-the-with-statements.md @@ -0,0 +1,30 @@ +# When Things Don't Match The With Statements + +You set up a series of match statements in a `with` construct as a way of +avoiding a bunch of nested if statements. Inevitably you will be passing +data through that doesn't meet all of the match criteria. By default, the +`with` construct will short circuit and your program will continue from +there. + +You can, however, take more control over how you handle the _failure_ cases +by employing an `else` block. The `else` block works a lot like a case +statement. + +```elixir +with %{status_code: 200, body: body} <- HTTPoison.get!(url), + {:ok, decoded_body} <- Poison.decode(body) do + {:ok, decoded_body} +else + %{status_code: 401} -> + reauthenticate() + _ -> + log_error() +end +``` + +Here we are able to anticipate a _failure_ case and respond accordingly. For +everything else, we have a generic action that we take. + +See the [docs for +`with`](https://hexdocs.pm/elixir/Kernel.SpecialForms.html#with/1) for more +details.