Try rescue pattern matching not working

I try to do the following:

try do
  something_that_opens_a_file()
rescue
  %File.Error{reason: :enoent} ->
     do_something_here()
end

But I get “invalid “rescue” clause. The clause should match on an alias, a variable or be in the “var in [alias]” format”
Why?

For clarification, I cannot convert File.read! to File.read because it is external. Also, I want to avoid checking at a later stage and reraise the exception.

1 Like

One way of solving it is to have

try do
  something_that_opens_a_file()
rescue
  e in File.Error ->
     do_something_here(e.reason, anyotherargs)
end

And then have:
do_something_here(:enoent, .....), do: wtv...

3 Likes

Found the answer:

try do
  File.read! "nothing"
catch
  _kind, %File.Error{reason: :enoent} -> IO.puts "No file found"
end
3 Likes

Elixir really discourages catching errors and exceptions. Why not use case?

case File.read("nothing") do
  {:ok, contents} ->
  {:error, :enoent} ->
end
14 Likes

In my case it was a library that was doing this and not directly my code so I have no choice. But yes that would be the best solution otherwise.

1 Like