Skip to content
This repository was archived by the owner on Jul 25, 2024. It is now read-only.

How can I return an error to the client with a mutation? #64

Closed
dre1080 opened this issue Feb 29, 2016 · 4 comments
Closed

How can I return an error to the client with a mutation? #64

dre1080 opened this issue Feb 29, 2016 · 4 comments

Comments

@dre1080
Copy link

dre1080 commented Feb 29, 2016

Whenever I execute a mutation I can never seem to produces errors as stated here: https://facebook.github.io/graphql/#sec-Errors

How do I produce errors?

@aweiker
Copy link
Member

aweiker commented Mar 1, 2016

Did a bunch of tracking down and GraphQL.Execution.Executor.report_error/2 mutates the context parameter and returns a new context, but we don't actually use the new value that has the error in it.

When using put_in/3 it returns a new value with the change.

@dre1080
Copy link
Author

dre1080 commented Mar 1, 2016

@aweiker I saw the same thing.

I finally came up with a solution.
At the moment, this is what I'm doing for errors:

defmodule GraphQL.InvalidChangesetError do
  @moduledoc """
  Exception raised when Ecto Changeset is invalid.
  """

  defexception plug_status: 422, message: "invalid changeset", changeset: nil, errors: %{}

  @doc false
  def exception(opts) do
    changeset = Keyword.fetch!(opts, :changeset)
    errors = changeset.errors

    %GraphQL.InvalidChangesetError{
      message: "invalid changeset for (#{changeset.data.__struct__}): #{inspect errors}",
      changeset: changeset,
      errors: errors
    }
  end
end

These are errors that have to do with uniqueness & querying the db.

Then added the following to my ErrorView:

def render("422.json", assigns) do
    {_, _, _, stack} = hd(assigns[:stack])
    {field, message} = hd(assigns[:reason].errors)
    %{errors: [%{message: "#{field} #{message}",
                 file: to_string(stack[:file]),
                 line: stack[:line]}]}
end

Now whenever I need to produce an error to the client I raise/2 a GraphQL.InvalidChangesetError like so:

raise GraphQL.InvalidChangesetError, changeset: changeset

This now returns an appropriate error object that Relay can understand.

@joshprice
Copy link
Member

Related to #56

@bringking
Copy link

Any status on this? From reading the spec, if we can't bubble errors during query execution, then the library isn't spec compliant.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants