File tree Expand file tree Collapse file tree 2 files changed +32
-1
lines changed Expand file tree Collapse file tree 2 files changed +32
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010For 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
Original file line number Diff line number Diff line change 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.
You can’t perform that action at this time.
0 commit comments