From ccf22d0d9c368b9df72a2fe125eaf46200e9e0e7 Mon Sep 17 00:00:00 2001 From: James Sharp Date: Fri, 15 Mar 2024 18:35:42 +0000 Subject: [PATCH] Extend err_if_nil --- lib/oxide.ex | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/oxide.ex b/lib/oxide.ex index 8437684..9fdd22d 100644 --- a/lib/oxide.ex +++ b/lib/oxide.ex @@ -184,17 +184,26 @@ defmodule Oxide.Result do @doc ~S""" Convert a maybe-nil value to a result. - Maps `nil` to `{:error, reason}` and any non-`nil` value to `{:ok, value}`. + Maps `nil` and `{:ok, nil}` to `{:error, reason}`, passes errors through and otherwise maps `value`, or {:ok, value}` to `{:ok, value}`. iex> %{"key" => "value"} |> Map.get("key") |> Result.err_if_nil(:notfound) {:ok, "value"} iex> %{"key" => "value"} |> Map.get("missing") |> Result.err_if_nil(:notfound) {:error, :notfound} + iex> {:ok, nil} |> Result.err_if_nil(:notfound) + {:error, :notfound} + iex> {:ok, "value"} |> Result.err_if_nil(:notfound) + {:ok, "value"} + iex> {:error, :badthing} |> Result.err_if_nil(:notfound) + {:error, :badthing} """ @spec err_if_nil(any(), any()) :: t() def err_if_nil(value, reason) def err_if_nil(value, reason) when is_nil(value), do: {:error, reason} + def err_if_nil({:ok, value}, reason) when is_nil(value), do: {:error, reason} + def err_if_nil({:ok, value}, _reason) when not is_nil(value), do: {:ok, value} + def err_if_nil({:error, reason}, _reason), do: {:error, reason} def err_if_nil(value, _reason) when not is_nil(value), do: {:ok, value} @doc ~S"""