Defining Your Own Exceptions

Exceptions in Elixir are basically records. You can define your own exceptions by creating a module. Inside it, use defexception to define the various fields in the exception, along with their default values. Because you’re creating a module, you can also add functions—often these are used to format the exception’s fields into meaningful messages.

Say we’re writing a library to talk to a Microsoft Kinect controller. It might want to raise an exception on various kinds of communication error. Some of these are permanent, but others are likely to be transient and can be retried. We’ll define our exception with its (required) message field and an additional can_retry field. We’ll also add a function that formats these ...

Get Programming Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.