Skip to content

Commit 0ec5931

Browse files
committed
Add When Things Don't Match The With Statements as an elixir til
1 parent 72d58a6 commit 0ec5931

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010
For a steady stream of TILs from a variety of rocketeers, checkout
1111
[til.hashrocket.com](https://til.hashrocket.com/).
1212

13-
_784 TILs and counting..._
13+
_785 TILs and counting..._
1414

1515
---
1616

@@ -163,6 +163,7 @@ _784 TILs and counting..._
163163
- [Updating Values In A Map](elixir/updating-values-in-a-map.md)
164164
- [Using When Clauses In A With Construct](elixir/using-when-clauses-in-a-with-construct.md)
165165
- [Virtual Fields With Ecto Schemas](elixir/virtual-fields-with-ecto-schemas.md)
166+
- [When Things Don't Match The With Statements](elixir/when-things-dont-match-the-with-statements.md)
166167
- [Word Lists For Atoms](elixir/word-lists-for-atoms.md)
167168

168169
### Git
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# When Things Don't Match The With Statements
2+
3+
You set up a series of match statements in a `with` construct as a way of
4+
avoiding a bunch of nested if statements. Inevitably you will be passing
5+
data through that doesn't meet all of the match criteria. By default, the
6+
`with` construct will short circuit and your program will continue from
7+
there.
8+
9+
You can, however, take more control over how you handle the _failure_ cases
10+
by employing an `else` block. The `else` block works a lot like a case
11+
statement.
12+
13+
```elixir
14+
with %{status_code: 200, body: body} <- HTTPoison.get!(url),
15+
{:ok, decoded_body} <- Poison.decode(body) do
16+
{:ok, decoded_body}
17+
else
18+
%{status_code: 401} ->
19+
reauthenticate()
20+
_ ->
21+
log_error()
22+
end
23+
```
24+
25+
Here we are able to anticipate a _failure_ case and respond accordingly. For
26+
everything else, we have a generic action that we take.
27+
28+
See the [docs for
29+
`with`](https://hexdocs.pm/elixir/Kernel.SpecialForms.html#with/1) for more
30+
details.

0 commit comments

Comments
 (0)