OK icon indicating copy to clipboard operation
OK copied to clipboard

Clarify semantics of OK.try rescue clause

Open nietaki opened this issue 7 years ago • 5 comments

I think it's worth it to make it clearer in the docs what happens in the "unhappy path" in OK.try - the wrapped errors get unwrapped and "rescued", but non-tagged errors cause a runtime error.

For example the first test case will succeed, but the second one will fail:

  test "OK.try with wrapped error" do
    res = OK.try do
      foo <- {:error, :foo}
    after
      :unwrapped_success
    rescue
      :foo -> :got_foo
    end

    assert res == :got_foo
  end

  test "OK.try with unwrapped error" do
    bar = fn -> :bar end

    res = OK.try do
      bar <- bar.() # will cause runtime error!
    after
      :unwrapped_success
    rescue
      :bar -> :got_bar
    end

    assert res == :got_bar
  end

For more clarity it might be worth adding that safe_div/2 used in all examples returns {:ok, integer()} | {:error, atom()}, so in the division by zero case it will return {:error, :zero_division}, not :zero_division

nietaki avatar Jan 19 '18 15:01 nietaki

Always approve more clarity in the docs :whale:

CrowdHailer avatar Jan 19 '18 20:01 CrowdHailer

Did you want to add anything to the docs for this?

CrowdHailer avatar Aug 26 '18 10:08 CrowdHailer

I just saw this library in Elixir Radar, and I also found the "rescued" part confusing. @CrowdHailer I think you should've picked a different word, as people might get confused as to whether the "rescue" part will capture runtime errors and other exceptional errors as the regular try/rescue does. Perhaps:

OK.try do
after
except
end

would've been clearer.

That's just me. Other than this the library seems cool!

walkr avatar Sep 17 '18 05:09 walkr

@walkr rescue has to be chosen from one of the reserved words that can be used in do/end blocks https://github.com/elixir-lang/elixir/blob/master/lib/elixir/pages/Syntax%20Reference.md

However if there is anything you think could be clearer as a beginner to the library please do open a PR. even one sentence in the docs might help someone.

I'm quite along way from having by beginners hat on with this library so am probably not the best person to do it.

CrowdHailer avatar Sep 17 '18 07:09 CrowdHailer

@CrowdHailer Ah okay, got it! Thanks for the explanation.

walkr avatar Sep 17 '18 17:09 walkr