Skip to content

Commit 0a7e76a

Browse files
committed
Add Context#add_error
Allows errors to be added while returning value from resolver.
1 parent 9d4b6c1 commit 0a7e76a

File tree

4 files changed

+31
-0
lines changed

4 files changed

+31
-0
lines changed

lib/graphql/query/context.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,21 @@ def [](key)
4545
def []=(key, value)
4646
@values[key] = value
4747
end
48+
49+
# Add error to current field resolution.
50+
# @param error [GraphQL::ExecutionError] an execution error
51+
# @return [void]
52+
def add_error(error)
53+
unless error.is_a?(ExecutionError)
54+
raise TypeError, "expected error to be a ExecutionError, but was #{error.class}"
55+
end
56+
57+
error.ast_node = irep_node.ast_node
58+
error.path = irep_node.path
59+
errors << error
60+
61+
nil
62+
end
4863
end
4964
end
5065
end

spec/graphql/execution_error_spec.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
}
4545
}
4646
executionError
47+
valueWithExecutionError
4748
}
4849
4950
fragment similarCheeseFields on Cheese {
@@ -90,6 +91,7 @@
9091
]
9192
},
9293
"executionError" => nil,
94+
"valueWithExecutionError" => 0
9395
},
9496
"errors"=>[
9597
{
@@ -127,6 +129,11 @@
127129
"locations"=>[{"line"=>41, "column"=>7}],
128130
"path"=>["executionError"]
129131
},
132+
{
133+
"message"=>"Could not fetch latest value",
134+
"locations"=>[{"line"=>42, "column"=>7}],
135+
"path"=>["valueWithExecutionError"]
136+
},
130137
]
131138
}
132139
assert_equal(expected_result, result)

spec/graphql/introspection/schema_type_spec.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
{"name"=>"milk"},
3333
{"name"=>"root"},
3434
{"name"=>"searchDairy"},
35+
{"name"=>"valueWithExecutionError"},
3536
]
3637
},
3738
"mutationType"=> {

spec/support/dairy_app.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,14 @@ def self.create(type:, data:)
297297
resolve ->(t, a, c) { raise(GraphQL::ExecutionError, "There was an execution error") }
298298
end
299299

300+
field :valueWithExecutionError do
301+
type !GraphQL::INT_TYPE
302+
resolve ->(t, a, c) {
303+
c.add_error(GraphQL::ExecutionError.new("Could not fetch latest value"))
304+
return 0
305+
}
306+
end
307+
300308
# To test possibly-null fields
301309
field :maybeNull, MaybeNullType do
302310
resolve ->(t, a, c) { OpenStruct.new(cheese: nil) }

0 commit comments

Comments
 (0)