How to create Ash Errors directly

Regarding the Error Handling documentation: Error Handling — ash v3.4.65

How do I create an error struct directly, as part of an {:error, error} tuple? For example, I have a Changeset.after_action() that needs to return an error for a not-found case, and an error for an unauthorized case. What is the correct way to specify those kinds of errors? Also, I want the error to show up in an AshGraphql response.

That is documented in this example here: Error Handling — ash v3.4.65

You can call TheException.exception(foo: :bar).

So you could use this exception in that case: Ash.Error.Query.NotFound — ash v3.4.65

That exception is displayed by AshGraphql.

To see if an exception is displayed by AshGraphql you can see if the AshGraphql.Error protocol is implemented for an instance of that error, or see the implementations here: ash_graphql/lib/error.ex at main · ash-project/ash_graphql · GitHub

There is also an AshGraphql specific guide on errors here Handling Errors — ash_graphql v1.7.2 that has an example of defining a custom exception that can be rendered in the GraphQL response.

We should add descriptions of the fields, or @type t to those exceptions, but if you click into the source its easy enough to see what fields can be provided:

use Splode.Error, fields: [:primary_key, :resource]

creating a custom exception would allow you to customize exactly how its represented in AshGraphql and what fields can be provided.

I think I understand now. The exception() function on the error modules takes a keyword list, even though the documentation for exception() shows it taking zero arguments. There is an example in the Error Handling page that shows calling Ash.Error.Changes.Required.exception() with a keyword list, and I wasn’t able to extrapolate that to the exception() functions on the other error modules. Now I understand. Thanks

1 Like

huh, you’re right I didn’t even notice that. I don’t know why it doesn’t show arguments to that function :thinking:

Found the problem, thanks for pointing it out. The next release will have the docs corrected.

1 Like