From b5aaeb6a2db0ab9e003f874e2cfa4048088c373d Mon Sep 17 00:00:00 2001 From: ardhitama Date: Tue, 14 Jul 2026 22:40:50 +0700 Subject: [PATCH] Improve error API and project quality --- .github/workflows/ci.yml | 88 +++++++++++ .gitignore | 54 ++++--- README.md | 153 +++++++++++++++++- lib/errx.ex | 333 ++++++++++++++++++++++++++++----------- mix.exs | 55 +++++-- mix.lock | 19 ++- test/errx_test.exs | 302 +++++++++++++++++------------------ 7 files changed, 700 insertions(+), 304 deletions(-) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..70e10b6 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,88 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + +permissions: + contents: read + +jobs: + quality: + name: Elixir ${{ matrix.elixir }} / OTP ${{ matrix.otp }} + runs-on: ubuntu-22.04 + env: + MIX_ENV: test + strategy: + fail-fast: false + matrix: + include: + - elixir: "1.14.5" + otp: "25.3" + - elixir: "1.20.2" + otp: "29.0.3" + dialyzer: true + + steps: + - uses: actions/checkout@v4 + + - uses: erlef/setup-beam@v1 + with: + elixir-version: ${{ matrix.elixir }} + otp-version: ${{ matrix.otp }} + + - name: Restore dependencies cache + uses: actions/cache@v4 + with: + path: deps + key: deps-${{ runner.os }}-${{ matrix.elixir }}-${{ matrix.otp }}-${{ hashFiles('mix.exs', 'mix.lock') }} + + - name: Restore build cache + uses: actions/cache@v4 + with: + path: _build + key: build-${{ runner.os }}-${{ matrix.elixir }}-${{ matrix.otp }}-${{ hashFiles('mix.exs', 'mix.lock') }} + + - run: mix deps.get + + - name: Check formatting + run: mix format --check-formatted || (mix format && git diff --exit-code) + + - name: Compile + run: | + set -o pipefail + mix compile --warnings-as-errors 2>&1 | tee compile.log + + - name: Test + run: | + set -o pipefail + mix test 2>&1 | tee test.log + + - run: mix credo --strict + - run: mix hex.build + + - name: Dialyzer + if: matrix.dialyzer == true + run: | + set -o pipefail + { + dialyzer --build_plt --output_plt .dialyzer_plt \ + --apps erts kernel stdlib compiler crypto parsetools + elixir_ebin="$(elixir -e 'IO.puts(:code.lib_dir(:elixir, :ebin))')" + dialyzer -Wno_unknown -pa "$elixir_ebin" \ + --add_to_plt --plt .dialyzer_plt "$elixir_ebin" + dialyzer --no_check_plt -pa "$elixir_ebin" \ + --plt .dialyzer_plt _build/test/lib/errx/ebin + } 2>&1 | tee dialyzer.log + + - name: Upload failure diagnostics + if: failure() + uses: actions/upload-artifact@v4 + with: + name: diagnostics-${{ matrix.elixir }}-${{ matrix.otp }} + path: | + compile.log + test.log + dialyzer.log + if-no-files-found: ignore diff --git a/.gitignore b/.gitignore index 2719b15..c0b51b6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,25 +1,29 @@ -# The directory Mix will write compiled artifacts to. -/_build/ - -# If you run "mix test --cover", coverage assets end up here. -/cover/ - -# The directory Mix downloads your dependencies sources to. -/deps/ - -# Where third-party dependencies like ExDoc output generated docs. -/doc/ - -# Ignore .fetch files in case you like to edit your project deps locally. -/.fetch - -# If the VM crashes, it generates a dump, let's ignore it too. -erl_crash.dump - -# Also ignore archive artifacts (built via "mix archive.build"). -*.ez - -# Ignore package tarball (built via "mix hex.build"). -errx-*.tar - -.elixir_ls/ +# The directory Mix will write compiled artifacts to. +/_build/ + +# If you run "mix test --cover", coverage assets end up here. +/cover/ + +# The directory Mix downloads your dependencies sources to. +/deps/ + +# Where third-party dependencies like ExDoc output generated docs. +/doc/ + +# Ignore .fetch files in case you like to edit your project deps locally. +/.fetch + +# If the VM crashes, it generates a dump, let's ignore it too. +erl_crash.dump + +# Also ignore archive artifacts (built via "mix archive.build"). +*.ez + +# Ignore package tarball (built via "mix hex.build"). +errx-*.tar + +.elixir_ls/ + +# Dialyzer PLTs generated by local quality checks. +*.plt +*.plt.hash diff --git a/README.md b/README.md index 294f99e..09af0d5 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,160 @@ # Errx -**TODO: Add description** +Errx enriches conventional Elixir `{:error, reason}` tuples with the caller +location, optional metadata, and a chain of causes. It keeps the tuple shape +used by `case`, `with`, and tagged-return APIs while preserving enough context +to understand where an error was created. + +Errx is currently pre-1.0. Minor releases may refine the public API, but +changes are documented and existing tuple-based workflows are kept compatible +where practical. ## Installation -If [available in Hex](https://hex.pm/docs/publish), the package can be installed -by adding `errx` to your list of dependencies in `mix.exs`: +Add `errx` to the dependencies in `mix.exs`: ```elixir def deps do [ - {:errx, "~> 0.1.0"} + {:errx, "~> 0.5"} ] end ``` -Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc) -and published on [HexDocs](https://hexdocs.pm). Once published, the docs can -be found at [https://hexdocs.pm/errx](https://hexdocs.pm/errx). +Errx 0.5 requires Elixir 1.14 or later. + +## Wrap errors + +```elixir +{:error, error} = Errx.wrap(:not_found) + +error.reason +#=> :not_found + +error.location +#=> %{ +#=> module: MyApp.Users, +#=> function: :fetch, +#=> arity: 1, +#=> file: "lib/my_app/users.ex", +#=> line: 42 +#=> } +``` + +`file` and `func` remain available as formatted compatibility fields. New code +should prefer the structured `location` map. + +Both raw reasons and standard error tuples are accepted: + +```elixir +Errx.wrap(:not_found) +Errx.wrap({:error, :not_found}) +``` + +Wrapping an existing Errx value is idempotent and preserves its original +location. + +## Match reasons + +Use `Errx.match/1` in patterns: + +```elixir +case Errx.wrap(:not_found) do + Errx.match(:not_found) -> :recover +end +``` + +Use `Errx.match/2` in assertions or ordinary expressions: + +```elixir +Errx.match(Errx.wrap(:not_found), {:error, :not_found}) +#=> true + +Errx.match(:not_found, :not_found) +#=> false +``` + +At least one argument must be an Errx value. Unrelated values return `false` +rather than raising. + +## Add metadata + +`put_metadata/2` replaces metadata explicitly: + +```elixir +error = Errx.put_metadata(:not_found, %{resource: "user", id: 123}) +Errx.metadata(error) +#=> %{resource: "user", id: 123} +``` + +`merge_metadata/2` merges maps and overwrites duplicate keys with the new +values: + +```elixir +:failure +|> Errx.put_metadata(%{request_id: "abc", retry: false}) +|> Errx.merge_metadata(%{retry: true}) +``` + +The older `metadata/2` function remains as a replacement alias for backwards +compatibility. + +## Chain causes + +The historical API accepts parent first and child second: + +```elixir +{:error, error} = Errx.wrap(:database_unavailable, :lookup_failed) + +error.reason +#=> :lookup_failed + +error.parent.reason +#=> :database_unavailable +``` + +`with_parent/2` provides the explicit child-first form: + +```elixir +Errx.with_parent(:lookup_failed, :database_unavailable) +``` + +When the child already has a parent chain, the new parent is appended rather +than replacing existing context. `Errx.cause/1` reads the immediate parent. +The struct field remains named `parent` in 0.x for compatibility; its semantic +meaning is the underlying cause. + +## Raise Errx exceptions + +```elixir +raise Errx, :not_found +raise Errx, "user was not found" +raise Errx, Errx.wrap(:not_found) +``` + +Binary attributes become the exception message. Other arbitrary attributes +are stored under `metadata.data`. + +## Location limitations + +Locations are collected from the current process stack trace. Errx scans for +the first frame outside the Errx and Process modules instead of relying on a +fixed stack index. Generated code, aggressive inlining, or unusual runtime +stack frames may still affect which caller is reported. + +## Development + +Run the complete local quality suite with: + +```shell +mix deps.get +mix quality +``` + +CI verifies formatting, warnings, tests, Credo, package construction, and a +Dialyzer pass. The matrix covers the oldest supported Elixir release and the +latest stable Elixir/OTP combination. + +## License +Errx is licensed under GPL-3.0-only. See `LICENSE`. diff --git a/lib/errx.ex b/lib/errx.ex index 700556d..34a1f55 100644 --- a/lib/errx.ex +++ b/lib/errx.ex @@ -1,150 +1,295 @@ defmodule Errx do - @type t :: %Errx{} - - defexception [:file, :func, :reason, :metadata, :parent] - - defp loc(stack) do - {mod, fname, farity, [file: file, line: line]} = - Process.info(self(), :current_stacktrace) |> elem(1) |> Enum.fetch!(stack) - - func = "#{mod}.#{fname}/#{farity}" - file = "#{file}:#{line}" - {func, file} + @moduledoc """ + Adds call-site context, metadata, and cause chains to conventional + `{:error, reason}` values. + + The public constructors return `{:error, %Errx{}}`, so wrapped failures + remain compatible with standard Elixir tuple-based error handling. + + ## Wrapping + + iex> {:error, error} = Errx.wrap(:not_found) + iex> error.reason + :not_found + iex> is_map(error.location) + true + + Existing wrapped errors are returned unchanged: + + iex> wrapped = Errx.wrap(:not_found) + iex> Errx.wrap(wrapped) == wrapped + true + + ## Matching + + iex> Errx.match(Errx.wrap(:not_found), {:error, :not_found}) + true + iex> Errx.match(:not_found, :not_found) + false + + ## Metadata and causes + + iex> {:error, error} = Errx.put_metadata(:not_found, %{resource: "user"}) + iex> error.metadata + %{resource: "user"} + + iex> {:error, error} = Errx.wrap(:database_unavailable, :lookup_failed) + iex> {error.reason, error.parent.reason} + {:lookup_failed, :database_unavailable} + """ + + @typedoc "Structured information about the first caller outside `Errx`." + @type location :: %{ + module: module(), + function: atom(), + arity: non_neg_integer(), + file: String.t() | nil, + line: pos_integer() | nil + } + + @typedoc "A contextual error value." + @type t :: %__MODULE__{ + file: String.t() | nil, + func: String.t() | nil, + location: location() | nil, + reason: term(), + metadata: term(), + parent: t() | nil + } + + defexception [:file, :func, :location, :reason, :metadata, :parent] + + @doc """ + Wraps a reason or `{:error, reason}` value with caller information. + + Passing an existing `%Errx{}` or `{:error, %Errx{}}` preserves the existing + value and its original location. + """ + @spec wrap(term()) :: {:error, t()} + def wrap(error) do + {:error, wrap_with_location(error, caller_location())} end - defp wrap_with_loc(error, stack_skip) do - {func, file} = loc(stack_skip) + @doc """ + Wraps a child error and associates a parent cause with it. - case error do - %Errx{} -> - error + Existing cause chains on the child are preserved. The new parent is appended + to the end of the chain rather than replacing an existing parent. + """ + @spec wrap(term(), term()) :: {:error, t()} + def wrap(parent_error, child_error) do + with_parent(child_error, parent_error) + end - {:error, %Errx{} = error} -> - error + @doc """ + Associates `parent_error` with `error` while preserving any existing chain. - {:error, reason} -> - %Errx{func: func, file: file, reason: reason} + This is the explicit, child-first equivalent of `wrap(parent, child)`. + """ + @spec with_parent(term(), term()) :: {:error, t()} + def with_parent(error, parent_error) do + location = caller_location() + child = wrap_with_location(error, location) + parent = wrap_with_location(parent_error, location) - reason -> - %Errx{func: func, file: file, reason: reason} - end + {:error, append_parent(child, parent)} end - @spec wrap(any) :: {:error, Errx.t()} - def wrap(error) do - {:error, wrap_with_loc(error, 4)} - end + @doc """ + Replaces metadata on an error. - @spec wrap(any, any) :: {:error, Errx.t()} - def wrap(parent_error, child_error) do - {:error, %Errx{wrap_with_loc(child_error, 4) | parent: wrap_with_loc(parent_error, 4)}} + This function preserves the historical behavior of `metadata/2` while making + replacement semantics explicit. + """ + @spec put_metadata(term(), term()) :: {:error, t()} + def put_metadata(error, metadata) do + {:error, %__MODULE__{wrap_with_location(error, caller_location()) | metadata: metadata}} end - @spec metadata(any, any) :: {:error, Errx.t()} - def metadata(error, metadata) do - {:error, %Errx{wrap_with_loc(error, 4) | metadata: metadata}} + @doc """ + Merges map metadata into existing map metadata. + + Existing keys are overwritten by values from `metadata`. An error with `nil` + metadata is treated as having an empty map. Existing non-map metadata raises + `ArgumentError` rather than being silently discarded. + """ + @spec merge_metadata(term(), map()) :: {:error, t()} + def merge_metadata(error, metadata) when is_map(metadata) do + wrapped = wrap_with_location(error, caller_location()) + + merged = + case wrapped.metadata do + nil -> metadata + current when is_map(current) -> Map.merge(current, metadata) + current -> raise ArgumentError, "cannot merge map metadata into #{inspect(current)}" + end + + {:error, %__MODULE__{wrapped | metadata: merged}} end - @spec metadata(any) :: any - def metadata({:error, error}) do - case error do - %Errx{} -> - error.metadata + @doc """ + Replaces metadata on an error. - _ -> - nil - end - end + Kept for backwards compatibility. Prefer `put_metadata/2` when writing new + code because its name makes replacement behavior clear. + """ + @spec metadata(term(), term()) :: {:error, t()} + def metadata(error, metadata), do: put_metadata(error, metadata) + @doc "Returns metadata from a wrapped or bare `Errx`, or `nil` otherwise." + @spec metadata(term()) :: term() | nil def metadata(error) do - case error do - %Errx{} -> - error.metadata + case unwrap_errx(error) do + {:ok, %__MODULE__{metadata: metadata}} -> metadata + :error -> nil + end + end - _ -> - nil + @doc "Returns the parent cause from a wrapped or bare `Errx`, or `nil`." + @spec cause(term()) :: t() | nil + def cause(error) do + case unwrap_errx(error) do + {:ok, %__MODULE__{parent: parent}} -> parent + :error -> nil end end + @doc """ + Produces a pattern for matching an `Errx` reason in `case`, `with`, or + function clauses. + + case Errx.wrap(:not_found) do + Errx.match(:not_found) -> :matched + end + """ defmacro match(reason) do quote do {:error, %Errx{reason: unquote(reason)}} end end - @spec match(any, any) :: boolean - def match({:error, %Errx{reason: err1}}, {:error, err2}) do - err1 == err2 + @doc """ + Compares error reasons when at least one argument is an `Errx` value. + + Returns `false` for unrelated values instead of raising a + `FunctionClauseError`. + """ + @spec match(term(), term()) :: boolean() + def match(left, right) do + case {comparable_reason(left), comparable_reason(right)} do + {{:errx, left_reason}, {:errx, right_reason}} -> left_reason == right_reason + {{:errx, left_reason}, {:raw, right_reason}} -> left_reason == right_reason + {{:raw, left_reason}, {:errx, right_reason}} -> left_reason == right_reason + _ -> false + end end - def match({:error, err1}, {:error, %Errx{reason: err2}}) do - err1 == err2 + @impl true + def exception(attributes) when is_atom(attributes) do + wrap_with_location(attributes, caller_location()) end - def match(err1, {:error, %Errx{reason: err2}}) do - err1 == err2 + def exception(attributes) when is_binary(attributes) do + new(:errx_exception, caller_location(), %{message: attributes}) end - def match({:error, %Errx{reason: err1}}, err2) do - err1 == err2 - end + def exception(%__MODULE__{} = attributes), do: attributes + def exception({:error, %__MODULE__{} = attributes}), do: attributes - @impl true - def exception(attributes) when is_atom(attributes) do - wrap_with_loc(attributes, 3) + def exception(attributes) do + new(:errx_exception, caller_location(), %{data: attributes}) end @impl true - def exception(attributes) when is_bitstring(attributes) do - %Errx{wrap_with_loc(:errx_exception, 4) | metadata: %{message: attributes}} + def message({:error, %__MODULE__{} = error}), do: message(error) + + def message(%__MODULE__{} = error) do + case error do + %__MODULE__{metadata: %{message: message}} when is_binary(message) -> + message + + %__MODULE__{reason: reason} when is_atom(reason) -> + Atom.to_string(reason) + + %__MODULE__{reason: reason} -> + inspect(reason) + end end - @impl true - def exception(%Errx{} = attributes) do - attributes + defp wrap_with_location(%__MODULE__{} = error, _location), do: error + defp wrap_with_location({:error, %__MODULE__{} = error}, _location), do: error + defp wrap_with_location({:error, reason}, location), do: new(reason, location) + defp wrap_with_location(reason, location), do: new(reason, location) + + defp new(reason, location, metadata \\ nil) do + %__MODULE__{ + reason: reason, + metadata: metadata, + location: location, + file: legacy_file(location), + func: legacy_function(location) + } end - @impl true - def exception({:error, %Errx{} = attributes}) do - attributes + defp append_parent(%__MODULE__{parent: nil} = error, parent) do + %__MODULE__{error | parent: parent} end - @impl true - def exception(attributes) do - %Errx{wrap_with_loc(:errx_exception, 4) | metadata: %{data: attributes}} + defp append_parent(%__MODULE__{parent: existing} = error, parent) do + %__MODULE__{error | parent: append_parent(existing, parent)} end - @impl true - def message(%Errx{} = error) do - case error do - %Errx{metadata: %{message: reason}} when is_bitstring(reason) -> - reason + defp unwrap_errx({:error, %__MODULE__{} = error}), do: {:ok, error} + defp unwrap_errx(%__MODULE__{} = error), do: {:ok, error} + defp unwrap_errx(_error), do: :error - %Errx{reason: reason} when is_atom(reason) -> - Atom.to_string(reason) + defp comparable_reason({:error, %__MODULE__{reason: reason}}), do: {:errx, reason} + defp comparable_reason(%__MODULE__{reason: reason}), do: {:errx, reason} + defp comparable_reason({:error, reason}), do: {:raw, reason} + defp comparable_reason(reason), do: {:raw, reason} - %Errx{reason: reason} -> - inspect(reason) + defp caller_location do + case Process.info(self(), :current_stacktrace) do + {:current_stacktrace, stacktrace} -> Enum.find_value(stacktrace, &external_location/1) + _ -> nil + end + end - _ -> - inspect(error) + defp external_location({module, function, arity_or_arguments, details}) do + if module in [__MODULE__, Process] do + nil + else + details = if is_list(details), do: details, else: [] + + %{ + module: module, + function: function, + arity: arity(arity_or_arguments), + file: details |> Keyword.get(:file) |> normalize_file(), + line: Keyword.get(details, :line) + } end end - @impl true - def message({:error, %Errx{} = error}) do - case error do - %Errx{metadata: %{message: reason}} when is_bitstring(reason) -> - reason + defp external_location(_entry), do: nil - %Errx{reason: reason} when is_atom(reason) -> - Atom.to_string(reason) + defp arity(value) when is_integer(value), do: value + defp arity(arguments) when is_list(arguments), do: length(arguments) + defp arity(_value), do: 0 - %Errx{reason: reason} -> - inspect(reason) + defp normalize_file(nil), do: nil + defp normalize_file(file) when is_binary(file), do: file + defp normalize_file(file) when is_list(file), do: List.to_string(file) + defp normalize_file(file), do: to_string(file) - _ -> - inspect(error) - end + defp legacy_file(nil), do: nil + defp legacy_file(%{file: nil}), do: nil + defp legacy_file(%{file: file, line: nil}), do: file + defp legacy_file(%{file: file, line: line}), do: "#{file}:#{line}" + + defp legacy_function(nil), do: nil + + defp legacy_function(%{module: module, function: function, arity: arity}) do + "#{module}.#{function}/#{arity}" end end diff --git a/mix.exs b/mix.exs index 4ee512b..dae1893 100644 --- a/mix.exs +++ b/mix.exs @@ -1,39 +1,68 @@ defmodule Errx.MixProject do use Mix.Project + @version "0.5.0" + @source_url "https://github.com/ardhitama/errx" + def project do [ app: :errx, - version: "0.4.1", - elixir: "~> 1.10", + version: @version, + elixir: "~> 1.14", start_permanent: Mix.env() == :prod, deps: deps(), description: description(), - package: package() + package: package(), + name: "Errx", + source_url: @source_url, + docs: docs(), + aliases: aliases() ] end - def application do - [] + def cli do + [preferred_envs: [quality: :test, credo: :test]] end + def application, do: [] + defp deps do [ - {:ex_doc, ">= 0.0.0", only: :dev, runtime: false}, - {:credo, "~> 1.6", only: :dev, runtime: false} + {:ex_doc, ">= 0.34.0 and < 0.41.0", only: :dev, runtime: false}, + {:credo, "~> 1.7.19", only: [:dev, :test], runtime: false} ] end - defp description() do - "Initially build to reduce the author's pain point when using erlang tuple style error handling where it has no information of who create the error tuple." + defp description do + "Contextual error tuples with caller locations, metadata, and cause chains." end - defp package() do + defp package do [ - # These are the default files included in the package files: ~w(lib .formatter.exs mix.exs README* LICENSE*), - licenses: ["GNU GPL V3"], - links: %{"GitHub" => "https://github.com/ardhitama/errx"} + licenses: ["GPL-3.0-only"], + maintainers: ["ardhitama"], + links: %{"GitHub" => @source_url} + ] + end + + defp docs do + [ + main: "readme", + extras: ["README.md"], + source_ref: "v#{@version}" + ] + end + + defp aliases do + [ + quality: [ + "format --check-formatted", + "compile --warnings-as-errors", + "test", + "credo --strict", + "hex.build" + ] ] end end diff --git a/mix.lock b/mix.lock index 065aad5..2de2757 100644 --- a/mix.lock +++ b/mix.lock @@ -1,13 +1,12 @@ %{ "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"}, - "credo": {:hex, :credo, "1.7.7", "771445037228f763f9b2afd612b6aa2fd8e28432a95dbbc60d8e03ce71ba4446", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "8bc87496c9aaacdc3f90f01b7b0582467b69b4bd2441fe8aae3109d843cc2f2e"}, - "earmark": {:hex, :earmark, "1.4.3", "364ca2e9710f6bff494117dbbd53880d84bebb692dafc3a78eb50aa3183f2bfd", [:mix], [], "hexpm", "8cf8a291ebf1c7b9539e3cddb19e9cef066c2441b1640f13c34c1d3cfc825fec"}, - "earmark_parser": {:hex, :earmark_parser, "1.4.41", "ab34711c9dc6212dda44fcd20ecb87ac3f3fce6f0ca2f28d4a00e4154f8cd599", [:mix], [], "hexpm", "a81a04c7e34b6617c2792e291b5a2e57ab316365c2644ddc553bb9ed863ebefa"}, - "ex_doc": {:hex, :ex_doc, "0.34.2", "13eedf3844ccdce25cfd837b99bea9ad92c4e511233199440488d217c92571e8", [:mix], [{:earmark_parser, "~> 1.4.39", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "5ce5f16b41208a50106afed3de6a2ed34f4acfd65715b82a0b84b49d995f95c1"}, - "file_system": {:hex, :file_system, "1.0.1", "79e8ceaddb0416f8b8cd02a0127bdbababe7bf4a23d2a395b983c1f8b3f73edd", [:mix], [], "hexpm", "4414d1f38863ddf9120720cd976fce5bdde8e91d8283353f0e31850fa89feb9e"}, - "jason": {:hex, :jason, "1.4.4", "b9226785a9aa77b6857ca22832cffa5d5011a667207eb2a0ad56adb5db443b8a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "c5eb0cab91f094599f94d55bc63409236a8ec69a21a67814529e8d5f6cc90b3b"}, - "makeup": {:hex, :makeup, "1.1.2", "9ba8837913bdf757787e71c1581c21f9d2455f4dd04cfca785c70bbfff1a76a3", [:mix], [{:nimble_parsec, "~> 1.2.2 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "cce1566b81fbcbd21eca8ffe808f33b221f9eee2cbc7a1706fc3da9ff18e6cac"}, - "makeup_elixir": {:hex, :makeup_elixir, "0.16.2", "627e84b8e8bf22e60a2579dad15067c755531fea049ae26ef1020cad58fe9578", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "41193978704763f6bbe6cc2758b84909e62984c7752b3784bd3c218bb341706b"}, - "makeup_erlang": {:hex, :makeup_erlang, "1.0.1", "c7f58c120b2b5aa5fd80d540a89fdf866ed42f1f3994e4fe189abebeab610839", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "8a89a1eeccc2d798d6ea15496a6e4870b75e014d1af514b1b71fa33134f57814"}, - "nimble_parsec": {:hex, :nimble_parsec, "1.4.0", "51f9b613ea62cfa97b25ccc2c1b4216e81df970acd8e16e8d1bdc58fef21370d", [:mix], [], "hexpm", "9c565862810fb383e9838c1dd2d7d2c437b3d13b267414ba6af33e50d2d1cf28"}, + "credo": {:hex, :credo, "1.7.19", "cc52129665fc7c15143d47838fda0f9cd6dac9ceced7bf4da6f85fcbfe64b12a", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "2d8bc95d5a7bb99dd2613621d4f08c6a3575c3fd4b62e6a2b48a100352a557b8"}, + "earmark_parser": {:hex, :earmark_parser, "1.4.45", "cba8369ab2a1342e419bc2760eec731b17be828941dcf494045d44766227e1d5", [:mix], [], "hexpm", "d3ec045bf122965db20c0bdb420e19ee1415843135327124918473feb4b328e8"}, + "ex_doc": {:hex, :ex_doc, "0.40.3", "4a972ffe64bc07dc605af487e98fc19b72a4185f55ca031b94c0552d6071c1d9", [:mix], [{:earmark_parser, "~> 1.4.44", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "2756e357742fecd9749b489b85d67c9ce99c465f2e75728d9e6dc8d704b973de"}, + "file_system": {:hex, :file_system, "1.1.1", "31864f4685b0148f25bd3fbef2b1228457c0c89024ad67f7a81a3ffbc0bbad3a", [:mix], [], "hexpm", "7a15ff97dfe526aeefb090a7a9d3d03aa907e100e262a0f8f7746b78f8f87a5d"}, + "jason": {:hex, :jason, "1.4.5", "2e3a008590b0b8d7388c20293e9dcc9cf3e5d642fd2a114e4cbbb52e595d940a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "b0c823996102bcd0239b3c2444eb00409b72f6a140c1950bc8b457d836b30684"}, + "makeup": {:hex, :makeup, "1.2.2", "882d46dc0905e9ff7abf2aab61a7e6b3dcc555533977d8a23b06019e6c89ac94", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "9a1a24e5b343b8ae16abea0822c10a6f75da27af7fa802ada5251f7579bfccfa"}, + "makeup_elixir": {:hex, :makeup_elixir, "1.0.1", "e928a4f984e795e41e3abd27bfc09f51db16ab8ba1aebdba2b3a575437efafc2", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "7284900d412a3e5cfd97fdaed4f5ed389b8f2b4cb49efc0eb3bd10e2febf9507"}, + "makeup_erlang": {:hex, :makeup_erlang, "1.1.0", "835f7e60792e08824cda445639555d7bf1bbbddb1b60b306e33cb6f6db24dc74", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "1cd6780fb1dd1a03979abaed0fe82712b0625118fd5257d3ebbf73f960c73c3c"}, + "nimble_parsec": {:hex, :nimble_parsec, "1.4.2", "8efba0122db06df95bfaa78f791344a89352ba04baedd3849593bfce4d0dc1c6", [:mix], [], "hexpm", "4b21398942dda052b403bbe1da991ccd03a053668d147d53fb8c4e0efe09c973"}, } diff --git a/test/errx_test.exs b/test/errx_test.exs index 2cf3766..41bad8a 100644 --- a/test/errx_test.exs +++ b/test/errx_test.exs @@ -1,196 +1,188 @@ defmodule ErrxTest do - use ExUnit.Case + use ExUnit.Case, async: true + doctest Errx - test "wrap correctly" do - err = Errx.wrap(:failure_code) + describe "wrap/1" do + test "wraps raw reasons and error tuples" do + assert {:error, %Errx{reason: :failure, parent: nil} = raw} = Errx.wrap(:failure) + assert_location(raw, 1) - assert err == - {:error, - %Errx{ - file: "test/errx_test.exs:6", - func: "Elixir.ErrxTest.test wrap correctly/1", - reason: :failure_code - }} + assert {:error, %Errx{reason: :failure} = tuple} = Errx.wrap({:error, :failure}) + assert_location(tuple, 1) + end - err = Errx.wrap({:error, :failure_code}) + test "preserves existing Errx values" do + wrapped = Errx.wrap(:failure) + assert Errx.wrap(wrapped) == wrapped - assert err == - {:error, - %Errx{ - file: "test/errx_test.exs:16", - func: "Elixir.ErrxTest.test wrap correctly/1", - reason: :failure_code - }} + {:error, error} = wrapped + assert Errx.wrap(error) == wrapped + end - assert Errx.wrap(err) == - {:error, - %Errx{ - file: "test/errx_test.exs:16", - func: "Elixir.ErrxTest.test wrap correctly/1", - reason: :failure_code - }} + test "captures the first caller outside Errx" do + assert {:error, error} = wrap_from_helper() + assert_receive :wrapped + assert_location(error, :wrap_from_helper, 0) + end + end - {:error, err} = err + describe "cause chains" do + test "wrap/2 associates parent and child errors" do + assert {:error, %Errx{reason: :child, parent: %Errx{reason: :parent}}} = + Errx.wrap(:parent, :child) + end - assert Errx.wrap(%Errx{err | reason: :parent_failure}, err) == - {:error, - %Errx{ - file: "test/errx_test.exs:16", - func: "Elixir.ErrxTest.test wrap correctly/1", - reason: :failure_code, - parent: %Errx{ - file: "test/errx_test.exs:16", - func: "Elixir.ErrxTest.test wrap correctly/1", - parent: nil, - reason: :parent_failure - } - }} + test "with_parent/2 is the explicit child-first API" do + assert {:error, %Errx{reason: :child, parent: %Errx{reason: :parent}} = error} = + Errx.with_parent(:child, :parent) - assert Errx.wrap(:parent_error, :child_error) == - {:error, - %Errx{ - file: "test/errx_test.exs:50", - func: "Elixir.ErrxTest.test wrap correctly/1", - reason: :child_error, - parent: %Errx{ - file: "test/errx_test.exs:50", - func: "Elixir.ErrxTest.test wrap correctly/1", - parent: nil, - reason: :parent_error - } - }} + assert %Errx{reason: :parent} = Errx.cause(error) + assert %Errx{reason: :parent} = Errx.cause({:error, error}) + end - assert Errx.wrap({:error, :parent_error}, :child_error) == - {:error, - %Errx{ - file: "test/errx_test.exs:64", - func: "Elixir.ErrxTest.test wrap correctly/1", - reason: :child_error, - parent: %Errx{ - file: "test/errx_test.exs:64", - func: "Elixir.ErrxTest.test wrap correctly/1", - parent: nil, - reason: :parent_error - } - }} + test "preserves an existing cause chain" do + {:error, child} = Errx.wrap(:existing_parent, :child) - assert Errx.wrap(err, :child_error) == - {:error, + assert {:error, %Errx{ - file: "test/errx_test.exs:78", - func: "Elixir.ErrxTest.test wrap correctly/1", - reason: :child_error, + reason: :child, parent: %Errx{ - file: "test/errx_test.exs:16", - func: "Elixir.ErrxTest.test wrap correctly/1", - parent: nil, - reason: :failure_code + reason: :existing_parent, + parent: %Errx{reason: :oldest_parent} } - }} + }} = Errx.with_parent(child, :oldest_parent) + end + end - err1 = Errx.wrap({:error, :failure_code1}) - err2 = Errx.wrap(err1, {:error, :failure_code2}) - err3 = Errx.wrap({:error, :failure_code3}) + describe "matching" do + test "supports pattern matching" do + assert (case Errx.wrap(:failure) do + Errx.match(:failure) -> true + end) + end - assert Errx.wrap(err2, err3) == - {:error, - %Errx{ - file: "test/errx_test.exs:94", - func: "Elixir.ErrxTest.test wrap correctly/1", - parent: %Errx{ - file: "test/errx_test.exs:93", - func: "Elixir.ErrxTest.test wrap correctly/1", - parent: %Errx{ - file: "test/errx_test.exs:92", - func: "Elixir.ErrxTest.test wrap correctly/1", - parent: nil, - reason: :failure_code1 - }, - reason: :failure_code2 - }, - reason: :failure_code3 - }} - end + test "compares wrapped and raw reasons" do + left = Errx.wrap(:failure) + right = Errx.wrap(:failure) + different = Errx.wrap(:different) + + assert Errx.match(left, right) + assert Errx.match(left, {:error, :failure}) + assert Errx.match({:error, :failure}, left) + assert Errx.match(left, :failure) + assert Errx.match(:failure, left) + refute Errx.match(left, different) + end - test "allows errx to be matched in pattern matching" do - assert (case(Errx.wrap(:failure)) do - Errx.match(:failure) -> - true - end) + test "returns false for unrelated values" do + refute Errx.match(:failure, :failure) + refute Errx.match({:error, :failure}, {:error, :failure}) + refute Errx.match(:failure, :different) + end end - test "allows errx to be matched in exunit assertion" do - err = Errx.wrap({:error, :failure}) + describe "metadata" do + test "put_metadata/2 replaces metadata" do + assert {:error, %Errx{metadata: %{foo: :bar}} = error} = + Errx.put_metadata(:failure, %{foo: :bar}) - assert Errx.match(err, {:error, :failure}) - assert Errx.match({:error, :failure}, err) + assert Errx.metadata(error) == %{foo: :bar} + assert Errx.metadata({:error, error}) == %{foo: :bar} + assert Errx.metadata(:failure) == nil + end - assert Errx.match(err, :failure) - assert Errx.match(:failure, err) - end + test "metadata/2 remains a replacement alias" do + assert {:error, %Errx{metadata: :replacement}} = + :failure + |> Errx.put_metadata(%{foo: :bar}) + |> Errx.metadata(:replacement) + end - test "metadata enrichment" do - err = Errx.metadata(:treason, %{foo: :bar}) + test "merge_metadata/2 combines maps and overwrites duplicate keys" do + error = Errx.put_metadata(:failure, %{foo: :old, keep: true}) - assert err == - {:error, - %Errx{ - file: "test/errx_test.exs:134", - func: "Elixir.ErrxTest.test metadata enrichment/1", - metadata: %{foo: :bar}, - parent: nil, - reason: :treason - }} - - assert Errx.match(err, :treason) - assert Errx.metadata(err) == %{foo: :bar} + assert {:error, %Errx{metadata: %{foo: :new, keep: true, added: true}}} = + Errx.merge_metadata(error, %{foo: :new, added: true}) + end + + test "merge_metadata/2 rejects existing non-map metadata" do + error = Errx.put_metadata(:failure, :opaque) + + assert_raise ArgumentError, ~r/cannot merge map metadata/, fn -> + Errx.merge_metadata(error, %{foo: :bar}) + end + end end - test "raising exception" do - assert_raise Errx, fn -> - raise Errx + describe "exceptions" do + test "raises with default and atom reasons" do + assert_raise Errx, "errx_exception", fn -> raise Errx end + assert_raise Errx, "failure", fn -> raise Errx, :failure end end - assert_raise Errx, "error", fn -> - raise Errx, "error" + test "uses binary messages" do + assert_raise Errx, "failure", fn -> raise Errx, "failure" end end - assert_raise Errx, "failure", fn -> - raise Errx, Errx.wrap(:failure) + test "treats non-binary bitstrings as arbitrary data" do + bitstring = <<1::1>> + error = Errx.exception(bitstring) + + assert error.reason == :errx_exception + assert error.metadata == %{data: bitstring} end - try do - raise Errx - rescue - err in [Errx] -> - assert err.reason == :errx_exception - assert err.file =~ ~r/.+errx_test\.exs:.+/ + test "accepts wrapped errors" do + assert_raise Errx, "failure", fn -> raise Errx, Errx.wrap(:failure) end end - try do - raise Errx, Errx.wrap(:failure) - rescue - err in [Errx] -> - assert err.reason == :failure - assert err.file =~ ~r/.+errx_test\.exs:.+/ + test "stores arbitrary exception attributes as data" do + error = Errx.exception(%{status: 500}) + + assert error.reason == :errx_exception + assert error.metadata == %{data: %{status: 500}} + assert Errx.message(error) == "errx_exception" end - try do - raise Errx, :failure - rescue - err in [Errx] -> - assert err.reason == :failure - assert err.file =~ ~r/.+errx_test\.exs:.+/ + test "delegates tuple messages" do + error = Errx.exception("failure") + assert Errx.message({:error, error}) == "failure" end + end - try do - raise Errx, "failure" - rescue - err in [Errx] -> - assert err.reason == :errx_exception - assert err.metadata.message == "failure" - assert err.file =~ ~r/.+errx_test\.exs:.+/ + defp wrap_from_helper do + result = Errx.wrap(:failure) + send(self(), :wrapped) + result + end + + defp assert_location(error, arity), do: assert_location(error, nil, arity) + + defp assert_location( + %Errx{ + location: %{ + module: __MODULE__, + function: actual_function, + arity: arity, + file: location_file, + line: line + }, + file: legacy_file, + func: legacy_function + }, + function, + arity + ) do + if function != nil do + assert actual_function == function end + + assert is_atom(actual_function) + assert is_binary(location_file) + assert String.ends_with?(location_file, "test/errx_test.exs") + assert is_integer(line) and line > 0 + assert legacy_file == "#{location_file}:#{line}" + assert legacy_function == "#{__MODULE__}.#{actual_function}/#{arity}" end end