AshPhoenix.Inertia.Error (ash_phoenix v2.2.0)
View SourceProvides a mapping from an Ash Error type to a plain map that can be used with the Inertia.Controller.assign_errors/2
function.
Note this module is only available when the :inertia
dependency is included in your application.
Typical usage with Inertia
Inertia users will typically pass Ash errors directly into the Inertia.Controller.assign_errors/2
function in their controllers.
Internally the Inertia library will use the Inertia.Errors
protocol to transform the Ash Error to a plain map for JSON serialization.
def create(conn, params) do
case MyApp.Posts.create(params, actor: conn.assigns.current_user) do
{:ok, post} ->
redirect(conn, to: ~p"/posts/#{post.slug}")
{:error, errors} ->
conn
|> assign_errors(errors)
|> render_inertia("CreatePost")
end
end
The Inertia.Errors
protocol is implemented for common error types and the Ash error classes, such as Ash.Error.Invalid
and Ash.Error.Forbidden
.
If you have a situation where there is no protocol implementation for your error type, you may need to call Ash.Error.to_error_class/1
on the error
first, before passing it to Inertia.Controller.assign_errors/2
, or providing an implementation of the Inertia.Errors
protocol for the error type.
Summary
Functions
Converts an error, or list of errors to a map of error field to error message.
Functions
@spec to_errors(error_or_errors :: term(), message_func :: function()) :: %{ required(String.t()) => String.t() }
Converts an error, or list of errors to a map of error field to error message.
Nested field errors are flattened with the error path added as a dotted prefex, eg
%{
"user.contact.email_address" => "Is required"
}
Parameters
error_or_errors
(required) The error struct or listmessage_func
(optional) A function to transform a tuple of message string and variables map to a single string.
Examples
iex> AshPhoenix.Inertia.Error.to_errors(
iex> %Ash.Error.Action.InvalidArgument{
iex> path: [:customer, :contact],
iex> field: :email,
iex> message: "%{email} is already taken",
iex> vars: %{email: "acme@example.com"}
iex> }
iex>)
%{"customer.contact.email" => "acme@example.com is already taken"}
iex> AshPhoenix.Inertia.Error.to_errors(
iex> %Ash.Error.Invalid{
iex> errors: [
iex> %Ash.Error.Action.InvalidArgument{
iex> path: [:customer, :contact],
iex> field: :email,
iex> message: "%{email} is already taken",
iex> vars: %{email: "acme@example.com"}
iex> },
iex> %Ash.Error.Action.InvalidArgument{
iex> path: [:product],
iex> field: :sku,
iex> message: "%{product_name} is out of stock",
iex> vars: %{product_name: "acme powder"}
iex> }
iex> ]
iex> }
iex>)
%{
"customer.contact.email" => "acme@example.com is already taken",
"product.sku" => "acme powder is out of stock"
}