Inspecting a struct when raising an exception

in the library I am working on

  • There are a lot of structs which are wrappers of NIF ref.
  • I added Inspect implementation for these structs, in which some C functions are called.
  • These C functions might crash the VM with segmentfault, null ptr, etc. Often the inspection is not called by user code but Elixir compiler.
  • So I add an field safe_to_print to mark if this struct is safe to be inspected by calling C functions. The code roughly looks like this:
  defimpl Inspect do
    def inspect(%{safe_to_print: true, nif_ref: nif_ref}, _opts) do
      to_string_with_c_function(nif_ref) # this will crash the VM
    end

    def inspect(%{safe_to_print: false} = value, _opts) do
      Kernel.inspect(value, structs: false)
    end
  end
  • adding %{r | safe_to_print: false} here and there seems very smelly to me

My question

  • Is it possible to detect if an inspection is happening inside an exception? In my case if the struct is captured in the exception context, it means the native data usually has some serious problems and can’t be safely inspected.
  • or is there any more idiomatic way to handle this kind of situation?