This commit is contained in:
Zach Daniel 2024-03-14 17:21:48 -04:00
commit 18d22f9193
27 changed files with 1335 additions and 0 deletions

15
.check.exs Normal file
View file

@ -0,0 +1,15 @@
[
## all available options with default values (see `mix check` docs for description)
# parallel: true,
# skipped: true,
## list of tools (see `mix check` docs for defaults)
tools: [
## curated tools may be disabled (e.g. the check for compilation warnings)
# {:compiler, false},
## ...or adjusted (e.g. use one-line formatter for more compact credo output)
# {:credo, "mix credo --format oneline"},
{:doctor, false}
]
]

190
.credo.exs Normal file
View file

@ -0,0 +1,190 @@
# This file contains the configuration for Credo and you are probably reading
# this after creating it with `mix credo.gen.config`.
#
# If you find anything wrong or unclear in this file, please report an
# issue on GitHub: https://github.com/rrrene/credo/issues
#
%{
#
# You can have as many configs as you like in the `configs:` field.
configs: [
%{
#
# Run any config using `mix credo -C <name>`. If no config name is given
# "default" is used.
#
name: "default",
#
# These are the files included in the analysis:
files: %{
#
# You can give explicit globs or simply directories.
# In the latter case `**/*.{ex,exs}` will be used.
#
included: [
"lib/",
"src/",
"test/",
"web/",
"apps/*/lib/",
"apps/*/src/",
"apps/*/test/",
"apps/*/web/"
],
excluded: [~r"/_build/", ~r"/deps/", ~r"/node_modules/"]
},
#
# Load and configure plugins here:
#
plugins: [],
#
# If you create your own checks, you must specify the source files for
# them here, so they can be loaded by Credo before running the analysis.
#
requires: [],
#
# If you want to enforce a style guide and need a more traditional linting
# experience, you can change `strict` to `true` below:
#
strict: false,
#
# To modify the timeout for parsing files, change this value:
#
parse_timeout: 5000,
#
# If you want to use uncolored output by default, you can change `color`
# to `false` below:
#
color: true,
#
# You can customize the parameters of any check by adding a second element
# to the tuple.
#
# To disable a check put `false` as second element:
#
# {Credo.Check.Design.DuplicatedCode, false}
#
checks: [
#
## Consistency Checks
#
{Credo.Check.Consistency.ExceptionNames, []},
{Credo.Check.Consistency.LineEndings, []},
{Credo.Check.Consistency.ParameterPatternMatching, []},
# This check was erroring on sigils so I had to disable it
{Credo.Check.Consistency.SpaceAroundOperators, false},
{Credo.Check.Consistency.SpaceInParentheses, []},
{Credo.Check.Consistency.TabsOrSpaces, []},
#
## Design Checks
#
# You can customize the priority of any check
# Priority values are: `low, normal, high, higher`
#
{Credo.Check.Design.AliasUsage, false},
# You can also customize the exit_status of each check.
# If you don't want TODO comments to cause `mix credo` to fail, just
# set this value to 0 (zero).
#
{Credo.Check.Design.TagTODO, false},
{Credo.Check.Design.TagFIXME, []},
#
## Readability Checks
#
{Credo.Check.Readability.AliasOrder, []},
{Credo.Check.Readability.FunctionNames, []},
{Credo.Check.Readability.LargeNumbers, []},
{Credo.Check.Readability.MaxLineLength, [priority: :low, max_length: 120]},
{Credo.Check.Readability.ModuleAttributeNames, []},
{Credo.Check.Readability.ModuleDoc, []},
{Credo.Check.Readability.ModuleNames, []},
{Credo.Check.Readability.ParenthesesInCondition, false},
{Credo.Check.Readability.ParenthesesOnZeroArityDefs, []},
{Credo.Check.Readability.PredicateFunctionNames, false},
{Credo.Check.Readability.PreferImplicitTry, []},
{Credo.Check.Readability.RedundantBlankLines, []},
{Credo.Check.Readability.Semicolons, []},
{Credo.Check.Readability.SpaceAfterCommas, []},
{Credo.Check.Readability.StringSigils, []},
{Credo.Check.Readability.TrailingBlankLine, []},
{Credo.Check.Readability.TrailingWhiteSpace, []},
{Credo.Check.Readability.UnnecessaryAliasExpansion, []},
{Credo.Check.Readability.VariableNames, []},
#
## Refactoring Opportunities
#
{Credo.Check.Refactor.CondStatements, []},
{Credo.Check.Refactor.CyclomaticComplexity, false},
{Credo.Check.Refactor.FunctionArity, false},
{Credo.Check.Refactor.LongQuoteBlocks, false},
{Credo.Check.Refactor.MapInto, false},
{Credo.Check.Refactor.MatchInCondition, false},
{Credo.Check.Refactor.NegatedConditionsInUnless, []},
{Credo.Check.Refactor.NegatedConditionsWithElse, []},
{Credo.Check.Refactor.Nesting, [max_nesting: 10]},
{Credo.Check.Refactor.UnlessWithElse, []},
{Credo.Check.Refactor.WithClauses, []},
#
## Warnings
#
{Credo.Check.Warning.BoolOperationOnSameValues, []},
{Credo.Check.Warning.ExpensiveEmptyEnumCheck, []},
{Credo.Check.Warning.IExPry, []},
{Credo.Check.Warning.IoInspect, []},
{Credo.Check.Warning.LazyLogging, false},
{Credo.Check.Warning.MixEnv, false},
{Credo.Check.Warning.OperationOnSameValues, []},
{Credo.Check.Warning.OperationWithConstantResult, []},
{Credo.Check.Warning.RaiseInsideRescue, []},
{Credo.Check.Warning.UnusedEnumOperation, []},
{Credo.Check.Warning.UnusedFileOperation, []},
{Credo.Check.Warning.UnusedKeywordOperation, []},
{Credo.Check.Warning.UnusedListOperation, []},
{Credo.Check.Warning.UnusedPathOperation, []},
{Credo.Check.Warning.UnusedRegexOperation, []},
{Credo.Check.Warning.UnusedStringOperation, []},
{Credo.Check.Warning.UnusedTupleOperation, []},
{Credo.Check.Warning.UnsafeExec, []},
#
# Checks scheduled for next check update (opt-in for now, just replace `false` with `[]`)
#
# Controversial and experimental checks (opt-in, just replace `false` with `[]`)
#
# {Credo.Check.Readability.StrictModuleLayout,
# order: [:shortdoc, :moduledoc, :behaviour, :use, :defstruct, :type, :import, :alias, :require],
# ignore: [:module_attribute, :type]},
{Credo.Check.Readability.StrictModuleLayout, false},
{Credo.Check.Consistency.MultiAliasImportRequireUse, false},
{Credo.Check.Consistency.UnusedVariableNames, false},
{Credo.Check.Design.DuplicatedCode, false},
{Credo.Check.Readability.AliasAs, false},
{Credo.Check.Readability.MultiAlias, false},
{Credo.Check.Readability.Specs, false},
{Credo.Check.Readability.SinglePipe, false},
{Credo.Check.Readability.WithCustomTaggedTuple, false},
{Credo.Check.Refactor.ABCSize, false},
{Credo.Check.Refactor.Apply, false},
{Credo.Check.Refactor.AppendSingleItem, false},
{Credo.Check.Refactor.DoubleBooleanNegation, false},
{Credo.Check.Refactor.ModuleDependencies, false},
{Credo.Check.Refactor.NegatedIsNil, false},
{Credo.Check.Refactor.PipeChainStart, false},
{Credo.Check.Refactor.VariableRebinding, false},
{Credo.Check.Warning.LeakyEnvironment, false},
{Credo.Check.Warning.MapGetUnsafePass, false},
{Credo.Check.Warning.UnsafeToAtom, false}
#
# Custom checks can be created using `mix credo.gen.check`.
#
]
}
]
}

15
.doctor.exs Normal file
View file

@ -0,0 +1,15 @@
%Doctor.Config{
ignore_modules: [ ],
ignore_paths: [],
min_module_doc_coverage: 40,
min_module_spec_coverage: 0,
min_overall_doc_coverage: 48,
min_overall_moduledoc_coverage: 100,
min_overall_spec_coverage: 0,
exception_moduledoc_required: true,
raise: false,
reporter: Doctor.Reporters.Full,
struct_type_spec_required: true,
umbrella: false,
failed: false
}

4
.formatter.exs Normal file
View file

@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]

76
.github/CODE_OF_CONDUCT.md vendored Normal file
View file

@ -0,0 +1,76 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at zach@zachdaniel.dev. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

11
.github/CONTRIBUTING.md vendored Normal file
View file

@ -0,0 +1,11 @@
# Contributing to Ash
- We have a zero tolerance policy for failure to abide by our code of conduct. It is very standard, but please make sure
you have read it.
- Issues may be opened to propose new ideas, to ask questions, or to file bugs.
- Before working on a feature, please talk to the core team/the rest of the community via a proposal. We are
building something that needs to be cohesive and well thought out across all use cases. Our top priority is
supporting real life use cases like yours, but we have to make sure that we do that in a sustainable way. The
best compromise there is to make sure that discussions are centered around the _use case_ for a feature, rather
than the proposed feature itself.
- Before starting work, please comment on the issue to see if anyone is handling it. Be aware that if you've commented on an issue that you'd like to tackle it, but no one can reach you and/or demand/need arises sooner, it may still need to be done before you have a chance to finish. However, we will make all efforts to allow you to finish anything you claim.

27
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View file

@ -0,0 +1,27 @@
---
name: Bug report
about: Create a report to help us improve
title: ""
labels: bug, needs review
assignees: ""
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
A minimal set of resource definitions and calls that can reproduce the bug.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Runtime**
- Elixir version
- Erlang version
- OS
- Splode version
- any related extension versions
**Additional context**
Add any other context about the problem here.

View file

@ -0,0 +1,14 @@
---
name: Extension Proposal
about: Suggest/request a new extension
title: 'Extension Proposal: [Extension Name]'
labels: extension proposal, needs review
assignees: ''
---
** What is the purpose of the extension? **
High level purpose of the extension.
** How would it extend the DSL? **
Add an example of the DSL configuration this extension might add.

19
.github/ISSUE_TEMPLATE/proposal.md vendored Normal file
View file

@ -0,0 +1,19 @@
---
name: Proposal
about: Suggest an idea for this project
title: ""
labels: enhancement, needs review
assignees: ""
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

8
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View file

@ -0,0 +1,8 @@
# Contributor checklist
- [ ] Bug fixes include regression tests
- [ ] Chores
- [ ] Documentation changes
- [ ] Features include unit/acceptance tests
- [ ] Refactoring
- [ ] Update dependencies

13
.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,13 @@
name: Ash CI
on:
push:
tags:
- "v*"
branches: [main]
pull_request:
branches: [main]
jobs:
ash-ci:
uses: ash-project/ash/.github/workflows/ash-ci.yml@main
secrets:
HEX_API_KEY: ${{ secrets.HEX_API_KEY }}

26
.gitignore vendored Normal file
View file

@ -0,0 +1,26 @@
# 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").
splode-*.tar
# Temporary files, for example, from tests.
/tmp/

2
.tool-versions Normal file
View file

@ -0,0 +1,2 @@
erlang 26.0.2
elixir 1.16.0

1
FUNDING.yml Normal file
View file

@ -0,0 +1 @@
github: zachdaniel

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Zachary Scott Daniel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

5
README.md Normal file
View file

@ -0,0 +1,5 @@
# Splode
Splode helps you deal with errors and exceptions in your application that are aggregatable and consistent. The general pattern is that you use the `Splode` module as a top level aggregator of error classes, and whenever you return errors, you return one of your `Splode.Error` structs, or a string, or a keyword list. Then, if you want to group errors together, you can use your `Splode` module to do so. You can also use that module to turn any arbitrary value into a splode error.
See the [documentation on hex](https://hexdocs.pm/splode) for more information

15
config/config.exs Normal file
View file

@ -0,0 +1,15 @@
import Config
if Mix.env() == :dev do
config :git_ops,
mix_project: Splode.MixProject,
changelog_file: "CHANGELOG.md",
repository_url: "https://github.com/ash-project/splode",
# Instructs the tool to manage your mix version in your `mix.exs` file
# See below for more information
manage_mix_version?: true,
# Instructs the tool to manage the version in your README.md
# Pass in `true` to use `"README.md"` or a string to customize
manage_readme_version: ["README.md"],
version_tag_prefix: "v"
end

View file

@ -0,0 +1,111 @@
# Get Started with Splode
Splode helps you deal with errors and exceptions in your application that are aggregatable and consistent. The general pattern is that you use the `Splode` module as a top level aggregator of error classes, and whenever you return errors, you return one of your `Splode.Error` structs, or a string, or a keyword list. Then, if you want to group errors together, you can use your `Splode` module to do so. You can also use that module to turn any arbitrary value into a splode error.
More documentation for `Splode` will come in the future. This was extracted from Ash Framework so that it could be standardized across multiple packages. If you use Ash, you can use `Ash.Errors` to get the benefits of `Splode`.
For now, here is an example:
```elixir
defmodule MyApp.Errors do
use Splode, error_classes: [
invalid: MyApp.Errors.Invalid,
unknown: MyApp.Errors.Unknown
],
unknown_error: MyApp.Errors.Unknown.Unknown
end
# Error classes are splode errors with an `errors` key.
defmodule MyApp.Errors.Invalid do
use Splode.Error, fields: [:errors], class: :invalid
def splode_message(%{errors: errors}) do
Splode.ErrorClass.error_messages(errors)
end
end
# You will want to define an unknown error class,
# otherwise splode will use its own
defmodule MyApp.Errors.Unknown do
use Splode.Error, fields: [:errors], class: :unknown
def splode_message(%{errors: errors}) do
Splode.ErrorClass.error_messages(errors)
end
end
# This fallback exception will be used for unknown errors
defmodule MyApp.Errors.Unknown.Unknown do
use Splode.Error, fields: [:error], class: :unknown
# your unknown message should have an `error` key
def splode_message(%{error: error}) do
if is_binary(error) do
to_string(error)
else
inspect(error)
end
end
end
# Finally, you can create your own error classes
defmodule MyApp.Errors.InvalidArgument do
use Splode.Error, fields: [:name, :message], class: :invalid
def splode_message(%{name: name, message: message}) do
"Invalid argument #{name}: #{message}"
end
end
```
To use these exceptions in your application, the general pattern is to return errors in `:ok | :error` tuples, like so:
```elixir
def do_something(argument) do
if is_valid?(argument) do
{:ok, do_stuff()}
else
{:error,
MyApp.Errors.InvalidArgument.exception(
name: :argument,
message: "is invalid"
)}
end
end
```
Then, you can use `to_class`, and `to_error` tools to ensure that you have consistent error structures.
```elixir
def do_multiple_things(argument) do
results = [do(), multiple(), things()]
{results, errors} =
Enum.reduce(results, {[], []}, fn
{:ok, result}, {results, errors} ->
{[result | results], errors}
{:error, error} ->
# ensure each error is a splode error
# technically, `to_class` does this for you,
# this is just an example
{results, [MyApp.Errors.to_error(error) | errors]}
end)
case {results, errors} do
{results, []} ->
{:ok, results}
{_results, errors} ->
{:error, MyApp.Errors.to_class(errors)}
end
end
```
## Installation
```elixir
def deps do
[
{:splode, "~> 0.1.0"}
]
end
```

412
lib/splode.ex Normal file
View file

@ -0,0 +1,412 @@
defmodule Splode do
@moduledoc """
Use this module to create your error aggregator and handler.
For example:
```elixir
defmodule MyApp.Errors do
use Splode, error_classes: [
invalid: MyApp.Errors.Invalid,
unknown: MyApp.Errors.Unknown
],
unknown_error: MyApp.Errors.Unknown.Unknown
end
```
"""
@doc """
Returns true if the given value is a splode error.
"""
@callback splode_error?() :: boolean()
@doc """
Sets the path on the error or errors
"""
@callback set_path(Splode.Error.t() | [Splode.Error.t()]) ::
Splode.Error.t() | [Splode.Error.t()]
@doc """
Combine errors into an error class
"""
@callback to_class(any()) :: Splode.Error.t()
@doc """
Turns any value into a splode error
"""
@callback to_error(any()) :: Splode.Error.t()
@doc """
Converts a combination of a module and json input into an Splode exception.
This allows for errors to be serialized and deserialized
"""
@callback from_json(map) :: Splode.Error.t()
defmacro __using__(opts) do
quote bind_quoted: [opts: opts], generated: true, location: :keep do
@behaviour Splode
@error_classes Keyword.put_new(
List.wrap(opts[:error_classes]),
:unknown,
Splode.Error.Unknown
)
@unknown_error opts[:unknown_error] ||
raise(
ArgumentError,
"must supply the `unknown_error` option, pointing at a splode error to use in situations where we cannot convert an error."
)
if Enum.empty?(opts[:error_classes]) do
raise ArgumentError,
"must supply at least one error class to `use Splode`, via `use Splode, error_classes: [class: ModuleForClass]`"
end
@type error_class() ::
unquote(@error_classes |> Keyword.keys() |> Enum.reduce(&{:|, [], [&1, &2]}))
@type class_module() ::
unquote(@error_classes |> Keyword.values() |> Enum.reduce(&{:|, [], [&1, &2]}))
@type t :: %{
required(:__struct__) => module(),
required(:__exception__) => true,
required(:class) => error_class(),
required(:bread_crumbs) => list(String.t()),
required(:vars) => Keyword.t(),
required(:stacktrace) => Splode.Stacktrace.t() | nil,
required(:context) => map(),
optional(atom) => any
}
@type class :: %{
required(:__struct__) => class_module(),
required(:__exception__) => true,
required(:errors) => list(t()),
required(:class) => error_class(),
required(:bread_crumbs) => list(String.t()),
required(:vars) => Keyword.t(),
required(:stacktrace) => Splode.Stacktrace.t() | nil,
required(:context) => map(),
optional(atom) => any
}
@class_modules Keyword.values(@error_classes) |> Enum.reject(&is_nil/1)
@error_class_indices @error_classes |> Keyword.keys() |> Enum.with_index() |> Enum.into(%{})
@impl true
def set_path(errors, path) when is_list(errors) do
Enum.map(errors, &set_path(&1, path))
end
def set_path(error, path) when is_map(error) do
path = List.wrap(path)
error =
if Map.has_key?(error, :path) && is_list(error.path) do
%{error | path: path ++ error.path}
else
error
end
error =
if Map.has_key?(error, :changeset) && error.changeset do
%{
error
| changeset: %{error.changeset | errors: set_path(error.changeset.errors, path)}
}
else
error
end
if Map.has_key?(error, :errors) && is_list(error.errors) do
%{error | errors: Enum.map(error.errors, &set_path(&1, path))}
else
error
end
end
def set_path(error, _), do: error
@impl true
def splode_error?(%struct{}) do
struct.splode_error?()
rescue
_ ->
false
end
def splode_error?(_), do: false
@impl true
def to_class(value, opts \\ [])
def to_class(%struct{errors: [error]} = class, _opts) when struct in @class_modules do
if error.class == :special do
error
else
class
end
end
def to_class(value, opts) when not is_list(value) do
if splode_error?(value) && value.class == :special do
value
else
to_class([value], opts)
end
end
def to_class(values, opts) when is_list(values) do
errors =
if Keyword.keyword?(values) do
[to_error(values, Keyword.delete(opts, :bread_crumbs))]
else
Enum.map(values, &to_error(&1, Keyword.delete(opts, :bread_crumbs)))
end
if Enum.count_until(errors, 2) == 1 &&
Enum.at(errors, 0).class == :special do
[List.first(errors)]
else
values
|> flatten_preserving_keywords()
|> Enum.uniq_by(&clear_stacktraces/1)
|> Enum.map(fn value ->
if splode_error?(value) do
value
else
exception_opts =
if opts[:stacktrace] do
[error: value, stacktrace: %Splode.Stacktrace{stacktrace: opts[:stacktrace]}]
else
[error: value]
end
@unknown_error.exception(exception_opts)
end
end)
|> choose_error()
|> accumulate_bread_crumbs(opts[:bread_crumbs])
end
end
defp choose_error([]) do
@error_classes[:unknown].exception([])
end
defp choose_error(errors) do
errors = Enum.map(errors, &to_error/1)
[error | other_errors] =
Enum.sort_by(errors, fn error ->
# the second element here sorts errors that are already parent errors
{Map.get(@error_class_indices, error.class),
@error_classes[error.class] != error.__struct__}
end)
parent_error_module = @error_classes[error.class]
if parent_error_module == error.__struct__ do
%{error | errors: (error.errors || []) ++ other_errors}
else
parent_error_module.exception(errors: errors)
end
end
@impl true
def to_error(value, opts \\ [])
def to_error(list, opts) when is_list(list) do
if Keyword.keyword?(list) do
list
|> Keyword.take([:error, :vars])
|> Keyword.put_new(:error, list[:message])
|> Keyword.put_new(:value, list)
|> @unknown_error.exception()
|> add_stacktrace(opts[:stacktrace])
|> accumulate_bread_crumbs(opts[:bread_crumbs])
else
case list do
[item] ->
to_error(item, opts)
list ->
to_class(list, opts)
end
end
end
def to_error(error, opts) when is_binary(error) do
[error: error]
|> @unknown_error.exception()
|> Map.put(:stacktrace, nil)
|> add_stacktrace(opts[:stacktrace])
|> accumulate_bread_crumbs(opts[:bread_crumbs])
end
def to_error(other, opts) do
cond do
splode_error?(other) ->
other
|> add_stacktrace(opts[:stacktrace])
|> accumulate_bread_crumbs(opts[:bread_crumbs])
is_exception(other) ->
[error: Exception.format(:error, other)]
|> @unknown_error.exception()
|> Map.put(:stacktrace, nil)
|> add_stacktrace(opts[:stacktrace])
|> accumulate_bread_crumbs(opts[:bread_crumbs])
true ->
[error: "unknown error: #{inspect(other)}"]
|> @unknown_error.exception()
|> Map.put(:stacktrace, nil)
|> add_stacktrace(opts[:stacktrace])
|> accumulate_bread_crumbs(opts[:bread_crumbs])
end
end
defp flatten_preserving_keywords(list) do
if Keyword.keyword?(list) do
[list]
else
Enum.flat_map(list, fn item ->
cond do
Keyword.keyword?(item) ->
[item]
is_list(item) ->
flatten_preserving_keywords(item)
true ->
[item]
end
end)
end
end
defp add_stacktrace(%{stacktrace: _} = error, stacktrace) do
stacktrace =
case stacktrace do
%Splode.Stacktrace{stacktrace: nil} ->
nil
nil ->
nil
stacktrace ->
%Splode.Stacktrace{stacktrace: stacktrace}
end
%{error | stacktrace: stacktrace || error.stacktrace || fake_stacktrace()}
end
defp add_stacktrace(e, _), do: e
defp fake_stacktrace do
{:current_stacktrace, stacktrace} = Process.info(self(), :current_stacktrace)
%Splode.Stacktrace{stacktrace: Enum.drop(stacktrace, 3)}
end
defp accumulate_bread_crumbs(error, bread_crumbs) when is_list(bread_crumbs) do
bread_crumbs
|> Enum.reverse()
|> Enum.reduce(error, &accumulate_bread_crumbs(&2, &1))
end
defp accumulate_bread_crumbs(%{errors: [_ | _] = errors} = error, bread_crumbs)
when is_binary(bread_crumbs) do
updated_errors = accumulate_bread_crumbs(errors, bread_crumbs)
add_bread_crumbs(%{error | errors: updated_errors}, bread_crumbs)
end
defp accumulate_bread_crumbs(errors, bread_crumbs)
when is_list(errors) and is_binary(bread_crumbs) do
Enum.map(errors, &add_bread_crumbs(&1, bread_crumbs))
end
defp accumulate_bread_crumbs(error, bread_crumbs) do
add_bread_crumbs(error, bread_crumbs)
end
defp add_bread_crumbs(error, bread_crumbs) when is_list(bread_crumbs) do
bread_crumbs
|> Enum.reverse()
|> Enum.reduce(error, &add_bread_crumbs(&2, &1))
end
defp add_bread_crumbs(error, bread_crumb) when is_binary(bread_crumb) do
%{error | bread_crumbs: [bread_crumb | error.bread_crumbs]}
end
defp add_bread_crumbs(error, _) do
error
end
@impl true
def from_json(module, json) do
{handled, unhandled} = process_known_json_keys(json)
unhandled =
Map.update(unhandled, "vars", [], fn vars ->
Map.to_list(vars)
end)
json = Map.merge(unhandled, handled)
module.from_json(json)
end
defp process_known_json_keys(json) do
{handled, unhandled} = Map.split(json, ~w(field fields message path))
handled =
handled
|> update_if_present("field", &String.to_existing_atom/1)
|> update_if_present("fields", fn fields ->
fields
|> List.wrap()
|> Enum.map(&Splode.Error.atomize_safely/1)
end)
|> update_if_present("path", fn item ->
item
|> List.wrap()
|> Enum.map(fn
item when is_integer(item) ->
item
item when is_binary(item) ->
case Integer.parse(item) do
{integer, ""} -> integer
_ -> item
end
end)
end)
{handled, unhandled}
end
defp clear_stacktraces(%{stacktrace: stacktrace} = error) when not is_nil(stacktrace) do
clear_stacktraces(%{error | stacktrace: nil})
end
defp clear_stacktraces(%{errors: errors} = exception) when is_list(errors) do
%{exception | errors: Enum.map(errors, &clear_stacktraces/1)}
end
defp clear_stacktraces(error), do: error
defp update_if_present(handled, key, fun) do
if Map.has_key?(handled, key) do
Map.update!(handled, key, fun)
else
handled
end
end
end
end
end

108
lib/splode/error.ex Normal file
View file

@ -0,0 +1,108 @@
defmodule Splode.Error do
@moduledoc """
Use this module to create an aggregatable error.
For example:
```elixir
defmodule MyApp.Errors.InvalidArgument do
use Splode.Error, fields: [:name, :message], class: :invalid
def splode_message(%{name: name, message: message}) do
"Invalid argument \#{name}: \#{message}"
end
end
```
"""
@callback splode_error?() :: boolean()
@callback from_json(map) :: struct()
@callback splode_message(struct()) :: String.t()
@type t :: Exception.t()
@doc false
def atomize_safely(value) do
String.to_existing_atom(value)
rescue
_ ->
:unknown
end
defmacro __using__(opts) do
quote generated: true, bind_quoted: [opts: opts] do
@behaviour Splode.Error
if !opts[:class] do
raise "Must provide an error class for a splode error, i.e `use Splode.Error, class: :invalid`"
end
defexception List.wrap(opts[:fields]) ++
[
bread_crumbs: [],
vars: [],
path: [],
stacktrace: nil,
class: opts[:class]
]
@impl Splode.Error
def splode_error?, do: true
@impl Exception
def message(%{vars: vars} = exception) do
string = splode_message(exception)
string =
case Splode.ErrorClass.bread_crumb(exception.bread_crumbs) do
"" ->
string
context ->
context <> "\n" <> string
end
Enum.reduce(List.wrap(vars), string, fn {key, value}, acc ->
if String.contains?(acc, "%{#{key}}") do
String.replace(acc, "%{#{key}}", to_string(value))
else
acc
end
end)
end
@impl Exception
def exception(opts) do
opts =
if is_nil(opts[:stacktrace]) do
{:current_stacktrace, stacktrace} = Process.info(self(), :current_stacktrace)
Keyword.put(opts, :stacktrace, %Splode.Stacktrace{stacktrace: stacktrace})
else
opts
end
super(opts) |> Map.update(:vars, [], &Splode.Error.clean_vars/1)
end
@impl Splode.Error
def from_json(json) do
keyword =
json
|> Map.to_list()
|> Enum.map(fn {key, value} -> {Splode.Error.atomize_safely(key), value} end)
exception(keyword)
end
defoverridable exception: 1, from_json: 1
end
end
@doc false
def clean_vars(vars) when is_map(vars) do
clean_vars(Map.to_list(vars))
end
def clean_vars(vars) do
vars |> Kernel.||([]) |> Keyword.drop([:field, :message, :path])
end
end

86
lib/splode/error_class.ex Normal file
View file

@ -0,0 +1,86 @@
defmodule Splode.ErrorClass do
@moduledoc "Tools for working with error classes"
@doc "Creates a long form composite error message for a list of errors"
def error_messages(errors, opts \\ []) do
custom_message = opts[:custom_message]
generic_message =
errors
|> List.wrap()
|> Enum.group_by(& &1.class)
|> Enum.map_join("\n\n", fn {class, class_errors} ->
header = String.capitalize(to_string(class)) <> " Error\n\n"
header <>
Enum.map_join(class_errors, "\n", fn
error when is_binary(error) ->
"* #{error}"
%{stacktrace: %Splode.Stacktrace{stacktrace: stacktrace}} = class_error ->
bread_crumb(class_error.bread_crumbs) <>
"* #{Exception.message(class_error)}\n" <>
path(class_error) <>
Enum.map_join(stacktrace, "\n", fn stack_item ->
" " <> Exception.format_stacktrace_entry(stack_item)
end)
%{bread_crumbs: bread_crumbs} = class_error when is_list(bread_crumbs) ->
if is_exception(class_error) do
bread_crumb(class_error.bread_crumbs) <>
"* #{Exception.message(class_error)}\n" <>
path(class_error)
else
end
other ->
Exception.format(:error, other)
end)
end)
if custom_message do
custom =
custom_message
|> List.wrap()
|> Enum.map_join("\n", &"* #{&1}")
"\n\n" <> custom <> generic_message
else
generic_message
end
end
defp path(%{path: path}) when path not in [[], nil] do
" at " <> to_path(path) <> "\n"
end
defp path(_), do: ""
defp to_path(path) do
Enum.map_join(path, ", ", fn item ->
if is_list(item) do
"[#{to_path(item)}]"
else
if is_binary(item) || is_atom(item) || is_number(item) do
item
else
inspect(item)
end
end
end)
end
@doc false
def bread_crumb(nil), do: ""
def bread_crumb([]), do: ""
def bread_crumb(bread_crumbs) do
case Enum.filter(bread_crumbs, & &1) do
[] ->
""
bread_crumbs ->
"Bread Crumbs: " <> Enum.join(bread_crumbs, " > ") <> "\n"
end
end
end

12
lib/splode/stacktrace.ex Normal file
View file

@ -0,0 +1,12 @@
defmodule Splode.Stacktrace do
@moduledoc "A placeholder for a stacktrace so that we can avoid printing it everywhere"
defstruct [:stacktrace]
@type t :: %__MODULE__{stacktrace: list}
defimpl Inspect do
def inspect(_, _) do
"#Splode.Stacktrace<>"
end
end
end

16
lib/splode/unknown.ex Normal file
View file

@ -0,0 +1,16 @@
defmodule Splode.Error.Unknown do
@moduledoc "The default top level unknown error container"
use Splode.Error, fields: [:errors], class: :unknown
def splode_message(exception) do
Splode.ErrorClass.error_messages(exception.errors)
end
def exception(opts) do
if opts[:error] do
super(Keyword.update(opts, :errors, [opts[:error]], &[opts[:error] | &1]))
else
super(opts)
end
end
end

96
mix.exs Normal file
View file

@ -0,0 +1,96 @@
defmodule Splode.MixProject do
use Mix.Project
@version "0.1.0"
@description """
A "soft deprecated" tool for composing workflows with your Ash Framework resources
"""
def project do
[
app: :splode,
version: @version,
elixir: "~> 1.16",
start_permanent: Mix.env() == :prod,
elixirc_paths: elixirc_paths(Mix.env()),
deps: deps(),
docs: docs(),
package: package(),
description: @description,
source_url: "https://github.com/ash-project/splode",
homepage_url: "https://github.com/ash-project/splode"
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
defp package do
[
name: :ash_flow,
licenses: ["MIT"],
files: ~w(lib .formatter.exs mix.exs README* LICENSE*
CHANGELOG* documentation),
links: %{
GitHub: "https://github.com/ash-project/splode",
Discord: "https://discord.gg/HTHRaaVPUc",
Website: "https://ash-hq.org",
Forum: "https://elixirforum.com/c/elixir-framework-forums/ash-framework-forum"
}
]
end
defp docs do
[
extras: [
"documentation/tutorials/get-started-with-splode.md"
],
source_ref: "v#{@version}",
extra_section: "GUIDES",
before_closing_head_tag: fn type ->
if type == :html do
"""
<script>
if (location.hostname === "hexdocs.pm") {
var script = document.createElement("script");
script.src = "https://plausible.io/js/script.js";
script.setAttribute("defer", "defer")
script.setAttribute("data-domain", "ashhexdocs")
document.head.appendChild(script);
}
</script>
"""
end
end
]
end
defp elixirc_paths(:test) do
["lib", "test/support"]
end
defp elixirc_paths(_), do: ["lib"]
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# Dev/Test dependencies
{:ex_doc, github: "elixir-lang/ex_doc", only: [:dev, :test], runtime: false},
{:ex_check, "~> 0.12", only: [:dev, :test]},
{:credo, ">= 0.0.0", only: [:dev, :test], runtime: false},
{:dialyxir, ">= 0.0.0", only: [:dev, :test], runtime: false},
{:mimic, "~> 1.7", only: [:test]},
{:sobelow, ">= 0.0.0", only: [:dev, :test], runtime: false},
{:git_ops, "~> 2.5", only: [:dev, :test]},
{:mix_audit, ">= 0.0.0", only: [:dev, :test], runtime: false},
{:mix_test_watch, "~> 1.0", only: [:dev, :test], runtime: false},
{:benchee, "~> 1.1", only: [:dev, :test]},
{:doctor, "~> 0.21", only: [:dev, :test]}
]
end
end

28
mix.lock Normal file
View file

@ -0,0 +1,28 @@
%{
"benchee": {:hex, :benchee, "1.3.0", "f64e3b64ad3563fa9838146ddefb2d2f94cf5b473bdfd63f5ca4d0657bf96694", [:mix], [{:deep_merge, "~> 1.0", [hex: :deep_merge, repo: "hexpm", optional: false]}, {:statistex, "~> 1.0", [hex: :statistex, repo: "hexpm", optional: false]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "34f4294068c11b2bd2ebf2c59aac9c7da26ffa0068afdf3419f1b176e16c5f81"},
"bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"},
"credo": {:hex, :credo, "1.7.5", "643213503b1c766ec0496d828c90c424471ea54da77c8a168c725686377b9545", [: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", "f799e9b5cd1891577d8c773d245668aa74a2fcd15eb277f51a0131690ebfb3fd"},
"decimal": {:hex, :decimal, "2.1.1", "5611dca5d4b2c3dd497dec8f68751f1f1a54755e8ed2a966c2633cf885973ad6", [:mix], [], "hexpm", "53cfe5f497ed0e7771ae1a475575603d77425099ba5faef9394932b35020ffcc"},
"deep_merge": {:hex, :deep_merge, "1.0.0", "b4aa1a0d1acac393bdf38b2291af38cb1d4a52806cf7a4906f718e1feb5ee961", [:mix], [], "hexpm", "ce708e5f094b9cd4e8f2be4f00d2f4250c4095be93f8cd6d018c753894885430"},
"dialyxir": {:hex, :dialyxir, "1.4.3", "edd0124f358f0b9e95bfe53a9fcf806d615d8f838e2202a9f430d59566b6b53b", [:mix], [{:erlex, ">= 0.2.6", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "bf2cfb75cd5c5006bec30141b131663299c661a864ec7fbbc72dfa557487a986"},
"doctor": {:hex, :doctor, "0.21.0", "20ef89355c67778e206225fe74913e96141c4d001cb04efdeba1a2a9704f1ab5", [:mix], [{:decimal, "~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}], "hexpm", "a227831daa79784eb24cdeedfa403c46a4cb7d0eab0e31232ec654314447e4e0"},
"earmark_parser": {:hex, :earmark_parser, "1.4.39", "424642f8335b05bb9eb611aa1564c148a8ee35c9c8a8bba6e129d51a3e3c6769", [:mix], [], "hexpm", "06553a88d1f1846da9ef066b87b57c6f605552cfbe40d20bd8d59cc6bde41944"},
"erlex": {:hex, :erlex, "0.2.6", "c7987d15e899c7a2f34f5420d2a2ea0d659682c06ac607572df55a43753aa12e", [:mix], [], "hexpm", "2ed2e25711feb44d52b17d2780eabf998452f6efda104877a3881c2f8c0c0c75"},
"ex_check": {:hex, :ex_check, "0.16.0", "07615bef493c5b8d12d5119de3914274277299c6483989e52b0f6b8358a26b5f", [:mix], [], "hexpm", "4d809b72a18d405514dda4809257d8e665ae7cf37a7aee3be6b74a34dec310f5"},
"ex_doc": {:git, "https://github.com/elixir-lang/ex_doc.git", "a7185981b9e7ff4af35e62d8e41de968949716aa", []},
"file_system": {:hex, :file_system, "1.0.0", "b689cc7dcee665f774de94b5a832e578bd7963c8e637ef940cd44327db7de2cd", [:mix], [], "hexpm", "6752092d66aec5a10e662aefeed8ddb9531d79db0bc145bb8c40325ca1d8536d"},
"git_cli": {:hex, :git_cli, "0.3.0", "a5422f9b95c99483385b976f5d43f7e8233283a47cda13533d7c16131cb14df5", [:mix], [], "hexpm", "78cb952f4c86a41f4d3511f1d3ecb28edb268e3a7df278de2faa1bd4672eaf9b"},
"git_ops": {:hex, :git_ops, "2.6.0", "e0791ee1cf5db03f2c61b7ebd70e2e95cba2bb9b9793011f26609f22c0900087", [:mix], [{:git_cli, "~> 0.2", [hex: :git_cli, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.0", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "b98fca849b18aaf490f4ac7d1dd8c6c469b0cc3e6632562d366cab095e666ffe"},
"jason": {:hex, :jason, "1.4.1", "af1504e35f629ddcdd6addb3513c3853991f694921b1b9368b0bd32beb9f1b63", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "fbb01ecdfd565b56261302f7e1fcc27c4fb8f32d56eab74db621fc154604a7a1"},
"makeup": {:hex, :makeup, "1.1.1", "fa0bc768698053b2b3869fa8a62616501ff9d11a562f3ce39580d60860c3a55e", [:mix], [{:nimble_parsec, "~> 1.2.2 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "5dc62fbdd0de44de194898b6710692490be74baa02d9d108bc29f007783b0b48"},
"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, "0.1.5", "e0ff5a7c708dda34311f7522a8758e23bfcd7d8d8068dc312b5eb41c6fd76eba", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "94d2e986428585a21516d7d7149781480013c56e30c6a233534bedf38867a59a"},
"mimic": {:hex, :mimic, "1.7.4", "cd2772ffbc9edefe964bc668bfd4059487fa639a5b7f1cbdf4fd22946505aa4f", [:mix], [], "hexpm", "437c61041ecf8a7fae35763ce89859e4973bb0666e6ce76d75efc789204447c3"},
"mix_audit": {:hex, :mix_audit, "2.1.2", "6cd5c5e2edbc9298629c85347b39fb3210656e541153826efd0b2a63767f3395", [:make, :mix], [{:jason, "~> 1.1", [hex: :jason, repo: "hexpm", optional: false]}, {:yaml_elixir, "~> 2.9", [hex: :yaml_elixir, repo: "hexpm", optional: false]}], "hexpm", "68d2f06f96b9c445a23434c9d5f09682866a5b4e90f631829db1c64f140e795b"},
"mix_test_watch": {:hex, :mix_test_watch, "1.2.0", "1f9acd9e1104f62f280e30fc2243ae5e6d8ddc2f7f4dc9bceb454b9a41c82b42", [:mix], [{:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}], "hexpm", "278dc955c20b3fb9a3168b5c2493c2e5cffad133548d307e0a50c7f2cfbf34f6"},
"nimble_parsec": {:hex, :nimble_parsec, "1.4.0", "51f9b613ea62cfa97b25ccc2c1b4216e81df970acd8e16e8d1bdc58fef21370d", [:mix], [], "hexpm", "9c565862810fb383e9838c1dd2d7d2c437b3d13b267414ba6af33e50d2d1cf28"},
"sobelow": {:hex, :sobelow, "0.13.0", "218afe9075904793f5c64b8837cc356e493d88fddde126a463839351870b8d1e", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "cd6e9026b85fc35d7529da14f95e85a078d9dd1907a9097b3ba6ac7ebbe34a0d"},
"statistex": {:hex, :statistex, "1.0.0", "f3dc93f3c0c6c92e5f291704cf62b99b553253d7969e9a5fa713e5481cd858a5", [:mix], [], "hexpm", "ff9d8bee7035028ab4742ff52fc80a2aa35cece833cf5319009b52f1b5a86c27"},
"yamerl": {:hex, :yamerl, "0.10.0", "4ff81fee2f1f6a46f1700c0d880b24d193ddb74bd14ef42cb0bcf46e81ef2f8e", [:rebar3], [], "hexpm", "346adb2963f1051dc837a2364e4acf6eb7d80097c0f53cbdc3046ec8ec4b4e6e"},
"yaml_elixir": {:hex, :yaml_elixir, "2.9.0", "9a256da867b37b8d2c1ffd5d9de373a4fda77a32a45b452f1708508ba7bbcb53", [:mix], [{:yamerl, "~> 0.10", [hex: :yamerl, repo: "hexpm", optional: false]}], "hexpm", "0cb0e7d4c56f5e99a6253ed1a670ed0e39c13fc45a6da054033928607ac08dfc"},
}

3
test/splode_test.exs Normal file
View file

@ -0,0 +1,3 @@
defmodule SplodeTest do
use ExUnit.Case
end

1
test/test_helper.exs Normal file
View file

@ -0,0 +1 @@
ExUnit.start()