Using Elixir's typespecs, how do I document in @spec
that a function may raise an exception instead of returning a value?
Types and specs. Elixir is a dynamically typed language, so all types in Elixir are checked at runtime. Nonetheless, Elixir comes with typespecs, which are a notation used for: declaring typed function signatures (also called specifications); declaring custom types.
For this purpose Elixir has @spec annotation to describe the specification of a function that will be checked by compiler. However in some cases specification is going to be quite big and complicated. If you would like to reduce complexity, you want to introduce a custom type definition.
At one time, no_return()
(listed in the Typespecs docs) was used in various places to document that a function might raise an exception - eg, File.copy!/2
in Elixir 1.6.
But those uses were removed by Devon Estes in this PR, and in approving it, José Valim said:
Any function can fail any time in face of invalid input.
I take this to mean that "this function could possibly raise an error" is always assumed and need not be documented in the typespec.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With