How to catch this specific type of error

I have an error like this:

Request: POST /teiserver/api/spads/balance_battle
** (exit) an exception was raised:
    ** (Enum.EmptyError) empty error

And want to catch it so I can log it. How should I go about this?

I’m confused because looking at this
https://hexdocs.pm/elixir/try-catch-and-rescue.html

its using an atom to find the error type. How to catch specifically Enum.EmptyError?

Enum.EmptyError is an atom. Does that help?

So this is correct code?

try do
  #my code
catch
  Enum.EmptyError -> Logger.error("add logs here")
end

I would expect you need to use rescue instead of catch.

Rescue for raises and catch for throws.

As en example from the linked page:

iex(31)> try do            
...(31)>   Enum.max(%{})
...(31)> rescue
...(31)>   e in Enum.EmptyError -> e
...(31)> end
%Enum.EmptyError{message: "empty error"}

or

iex(32)> try do
...(32)>   Enum.max(%{})
...(32)> rescue
...(32)>   Enum.EmptyError -> :we_are_empty
...(32)> end
:we_are_empty

You might also want to reraise as suggested by the same documentation:

try do
  ... some code ...
rescue
  e ->
    Logger.error(Exception.format(:error, e, __STACKTRACE__))
    reraise e, __STACKTRACE__
end
3 Likes