How do I add more than one error to the errors array in graphql-ruby?

371 views Asked by At

The documentation for GraphQl-Ruby states that top level errors are added to errors when raising an exception like this:

raise GraphQL::ExecutionError, "Can't continue with this query"

Which produces:

{
  "errors" => [
    {
      "message" => "Can't continue with this query",
      "locations" => [
        {
          "line" => 2,
          "column" => 10,
        }
      ],
      "path" => ["user", "login"],
    }
  ]
}

But I want to continue and add more than one error to the errors array. How do I do this (cleanly without a hack)

1

There are 1 answers

0
Rimian On

I found the answer somewhere in a rescue_from execution (can't remember where).

Basically, you need to push onto context.errors. You can do it in a prepare method on your input type or in the field.

Something like this:

class MyInputObject < GraphQL::Schema::InputObject
  def prepare
    context.errors << GraphQL::ExecutionError.new('bummer!') if bummer?
    context.errors << GraphQL::ExecutionError.new('darn it!') if darn_it?

    super
  end
end

For me, the errors were automatically raised and I didn't need to have any rescue_from anywhere in my implementation.

You might need to raise an execution error.

This will give you an array of errors as a response. Very useful if your error handling is a little complex.

See:
https://graphql-ruby.org/api-doc/2.0.0/GraphQL/Schema.html#rescue_from-class_method https://graphql-ruby.org/api-doc/2.0.0/GraphQL/Query/Context.html