jberling
How to ensure {:error, _} tuples are handled and not silently ignored?
First, sorry if this has already been asked in other topics. I couldn’t find it, but I would guess it’s a common thing to handle.
Let’s say I create a function that returns :ok or {:error, cause} — it’s a function that focuses on side effects. If I forget to handle the error (match the return value), the error will effectively be swallowed silently. How do you remember to handle the error? Or is this a bad pattern? Maybe the function should just raise an error instead?
It would be nice to catch this at compile time, but I understand it’s hard to do since Elixir is dynamic. However, Elixir is gradually becoming more statically typed. Will it be possible (or is it already possible) to check this statically?
Most Liked
LostKobrakai
The idea behind such a return pattern is that the function doesn’t want to decide how errors are to be handled, but delegates this responsibility to the caller of the function. So as you eluded to it’s the responsibility of the caller to deal with handling errors.
If you just do my_function() then indeed it could succeed or fail and nobody will be informed of either. Personally I’d argue ignoring return values is most often a code smell. It should likely be :ok = my_function() to raise in any non successful cases, or you could use case or with to deal with the error somehow.
There’s also a setting for dialyzer to warn if return values are not matched on forcing _ = my_function() for the cases, where indeed the return value is to be ignored.
dimitarvp
Yeah, this 100%. Elixir is not a statically-typed language and we can’t use sum types either.
Best we can do is make sure the code crashes early.
One very curious psychological effect of this is that people suddenly become good programmers again: “We can’t just assume a successful result!” – same people who were perfectly OK with just ignoring the return value.
So I found :ok = do_stuff() an amazing psychological hack: you make people pay attention and they also want proper error handling.
FlyingNoodle
If your program should crash you can assert like you suggested or you write a ! version that raises.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









