Skip to content

Support exceptions using defexception  #47

@matt-hobbs-prima

Description

@matt-hobbs-prima

It would be great if it were possible to leverage this library to also declare typed exceptions.

Exceptions are declared in the same way as Structs but using defexception instead of defstruct.

I can think of 2 ways to accomplish this:

  1. Use an option passed into the macro i.e. typedstruct exception: true do and pass that down to the __typedstruct__ call and replace the existing
defstruct @ts_fields

with

if unquote(!!opts[:exception]) do
  defexception @ts_fields
else
  defstruct @ts_fields
end
  1. Leverage the Plugin functionality.

Add a module attribute:

      Module.put_attribute(__MODULE__, :def_impl, &defstruct/1)

and similarly to the above, replace the line

defstruct @ts_fields

with

 @def_impl.(@ts_fields)

and then a plugin something like:

  defmodule DefExceptionPlugin do
    use TypedStruct.Plugin

    @impl true
    @spec init(keyword()) :: Macro.t()
    defmacro init(_opts) do
      quote do
        Module.put_attribute(__MODULE__, :def_impl, &defexception/1)
      end
    end
  end

I'm happy to raise a PR if you believe either of these are viable solutions.

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Status

    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions