Guy14

Guy14

AshJsonApi.Error translations

Hello community!

Yesterday I tried for a while to translate errors that comes from AshJsonApi controllers (which are AshJsonApi.Error structs, often built from other error structs such as Ash.Error.Changes.InvalidAttribute if I understood well).

What I used to achieve is to take precedence on AshJsonApi errors implemented in the lib, with dumb errors just for the try, such as this one:

defimpl AshJsonApi.ToJsonApiError, for: Ash.Error.Changes.InvalidAttribute do
  def to_json_api_error(error) do
    dbg("HERE")

    %AshJsonApi.Error{
      id: Ash.UUID.generate(),
      status_code: AshJsonApi.Error.class_to_status(error.class),
      code: "panic",
      title: "Panic",
      detail: error.message
      meta: Map.new(error.vars)
    }
  end
end

But the tradoffs of this new implementation are:

  • I get a compiler warning:

    warning: redefining module AshJsonApi.ToJsonApiError.Ash.Error.Changes.InvalidAttribute (current version loaded from _build/dev/lib/ash_json_api/ebin/Elixir.AshJsonApi.ToJsonApiError.Ash.Error.Changes.InvalidAttribute.beam)│16 │ defimpl AshJsonApi.ToJsonApiError, for: Ash.Error.Changes.InvalidAttribute do│ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~│└─ lib/prepair/to_ash_json_api_error.ex:16: AshJsonApi.ToJsonApiError.Ash.Error.Changes.InvalidAttribute (module)
    
  • I will lost eventual updates on the own library errors implementation

  • I do not manage to translate the error message with gettext (no compiler errors / warnings, but the displayed error is not yet the custom one I wrote, so it shows there is a problem in my implementation of the AshJsonApi.ToJsonApiError protocol):

    defimpl AshJsonApi.ToJsonApiError, for: Ash.Error.Changes.InvalidAttribute do
      use Gettext, backend: PrepairWeb.Gettext
    
      def to_json_api_error(error) do
        dbg("HERE")
    
        %AshJsonApi.Error{
          id: Ash.UUID.generate(),
          status_code: AshJsonApi.Error.class_to_status(error.class),
          code: "panic",
          title: "Panic",
          detail:
            dgettext(
              "errors",
              "must have the @ sign and no spaces"
            ),
          meta: Map.new(error.vars)
        }
      end
    end
    

I’ve searched on solutions but haven’t found one for now. The nearest to my problem thread I’ve read is this one: Translating Ash Error messages but I haven’t found a solution in it.

Does some of you already implemented translations for AshJsonApi errors?

To add more context, I can say for instance that this translations does work for AshErrors (not AshJsonApi) displayed in the Phoenix Liveview frontend:

defmodule Prepair.ValidationMacros do
  defmacro validate_email() do
    quote do
      use Gettext, backend: PrepairWeb.Gettext

      validate match(
                 :email,
                 ~S/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/
               ) do
        on [:create, :update]
        message dgettext("errors", "must have the @ sign and no spaces")
      end

But I wonder why the AshJsonApi error which comes from the Ash error triggered by that validation doesn’t send a translated error to the API.

Marked As Solved

zachdaniel

zachdaniel

Creator of Ash

I’ve pushed to main an improvement to mirror what we have with ash_graphql, which is an error_handler configuration you can set on each domain that would let you intercept and translate errors.


For gettext, you can’t use it in the DSL like that unfortunately. Those values are captured at compile time.

Also Liked

Guy14

Guy14

Just to let you know, it works perfectly for my needs!!

Thanks a lot again :orange_heart: And the added doc for Errors is well detailed :ok_hand:

And to anyone reading this post later, here is the solution, thanks to the new feature Zach added, that I’m using to translate API errors coming from AshJsonApi (generated) controllers:

# accounts.ex (Ash Domain)

defmodule Prepair.Accounts do
  use Ash.Domain, extensions: [AshJsonApi.Domain]

  json_api do
    routes do
      ...
    end

    error_handler {PrepairWeb.JsonApiErrorHandler, :handle_error, []}
  end
# json_api_error_handler.ex

defmodule PrepairWeb.JsonApiErrorHandler do
  use Gettext, backend: PrepairWeb.Gettext

  def handle_error(error, _context) do
    translated_detail = translate_error_detail(error.detail)
    %{error | detail: translated_detail}
  end

  defp translate_error_detail(detail) when is_binary(detail) do
    Gettext.dgettext(PrepairWeb.Gettext, "errors", detail)
  end

  defp translate_error_detail(detail), do: detail
end

Last Post!

Guy14

Guy14

Just to let you know, it works perfectly for my needs!!

Thanks a lot again :orange_heart: And the added doc for Errors is well detailed :ok_hand:

And to anyone reading this post later, here is the solution, thanks to the new feature Zach added, that I’m using to translate API errors coming from AshJsonApi (generated) controllers:

# accounts.ex (Ash Domain)

defmodule Prepair.Accounts do
  use Ash.Domain, extensions: [AshJsonApi.Domain]

  json_api do
    routes do
      ...
    end

    error_handler {PrepairWeb.JsonApiErrorHandler, :handle_error, []}
  end
# json_api_error_handler.ex

defmodule PrepairWeb.JsonApiErrorHandler do
  use Gettext, backend: PrepairWeb.Gettext

  def handle_error(error, _context) do
    translated_detail = translate_error_detail(error.detail)
    %{error | detail: translated_detail}
  end

  defp translate_error_detail(detail) when is_binary(detail) do
    Gettext.dgettext(PrepairWeb.Gettext, "errors", detail)
  end

  defp translate_error_detail(detail), do: detail
end

Where Next?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

Other popular topics Top

jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 40042 209
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44139 214
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

We're in Beta

About us Mission Statement