Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Message backend with user-friendly errors #29

Merged
merged 8 commits into from
Oct 20, 2023
Merged

Message backend with user-friendly errors #29

merged 8 commits into from
Oct 20, 2023

Conversation

solnic
Copy link
Owner

@solnic solnic commented Oct 18, 2023

This adds an error message backend that translates raw error tuples into user-friendly messages.

defmodule UserContract do
  use Drops.Contract

  schema do
    %{
      required(:name) => string(),
      required(:age) => integer(),
      required(:active) => boolean(),
      required(:tags) => list(string()),
      required(:settings) => map(:string),
      required(:address) => maybe(:string)
    }
  end
end

{:error, errors} = UserContract.conform(
  %{name: "Jane", age: 42, active: true, tags: ["red", :oops, "blue"], address: []}
)
{:error,
 [
   %Drops.Contract.Messages.Error.Sum{
     left: %Drops.Contract.Messages.Error.Type{
       path: [:address],
       text: "must be nil",
       meta: %{args: [nil, []], predicate: :type?}
     },
     right: %Drops.Contract.Messages.Error.Type{
       path: [:address],
       text: "must be a string",
       meta: %{args: [:string, []], predicate: :type?}
     }
   },
   %Drops.Contract.Messages.Error.Type{
     path: [:settings],
     text: "key must be present",
     meta: %{args: [:settings], predicate: :has_key?}
   },
   %Drops.Contract.Messages.Error.Type{
     path: [:tags, 1],
     text: "must be a string",
     meta: %{args: [:string, :oops], predicate: :type?}
   }
 ]}

Enum.map(errors, &to_string/1)
["address must be nil or address must be a string",
 "settings key must be present", "tags.1 must be a string"]

@solnic solnic added the feature label Oct 18, 2023
@solnic solnic added this to the v0.1.0 milestone Oct 18, 2023
@solnic solnic marked this pull request as ready for review October 20, 2023 08:15
@solnic solnic merged commit e8694b4 into main Oct 20, 2023
1 check passed
@solnic solnic deleted the message-backends branch October 20, 2023 08:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

1 participant