Raising a custom exception: module not available?

I can’t seem to make custom exceptions work. If I define a module like this:

defmodule MyApp.CustomException do
  defexception message: "Something bad happened."
end

then somewhere else in my app I reference it:

defmodule Something do
    alias MyApp.CustomException

    def do_something(nil) do
        raise CustomException
    end
end

I get this error:

function MyApp.CustomException.exception/1 is undefined (module MyApp.CustomException is not available)

What am I missing? I thought I was following https://elixir-lang.org/getting-started/try-catch-and-rescue.html correctly…

When I get this it’s usually a spelling issue for the module name.

1 Like

Your example works for me:

Erlang/OTP 21 [erts-10.3.1] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe]

Interactive Elixir (1.8.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> defmodule MyApp.CustomException do
...(1)>   defexception message: "Something bad happened."
...(1)> end
iex(2)> defmodule Something do
...(2)>     alias MyApp.CustomException
...(2)>
...(2)>     def do_something(nil) do
...(2)>         raise CustomException
...(2)>     end
...(2)> end
iex(3)> Something.do_something(nil)
** (MyApp.CustomException) Something bad happened.
    iex:6: Something.do_something/1
1 Like

FOUND IT. I accidentally put my module outside of lib/. Whoops.

2 Likes