From 9e332f06adcb1d6a4164562abcb3d1ae23c12e98 Mon Sep 17 00:00:00 2001 From: yn-misaki Date: Mon, 10 Feb 2025 13:56:00 +0900 Subject: [PATCH] Update error handling logic when TracedError when rescue_from with backtrace * Restore original 2.4.8 behavior for GraphQL::Backtrace::TracedError --- lib/graphql/schema.rb | 7 +++--- spec/graphql/schema_spec.rb | 44 +++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/lib/graphql/schema.rb b/lib/graphql/schema.rb index b60f884abe..04271d7c67 100644 --- a/lib/graphql/schema.rb +++ b/lib/graphql/schema.rb @@ -1114,9 +1114,6 @@ def error_handlers # @api private def handle_or_reraise(context, err) - if context[:backtrace] || using_backtrace - err = GraphQL::Backtrace::TracedError.new(err, context) - end handler = Execution::Errors.find_handler_for(self, err.class) if handler obj = context[:current_object] @@ -1128,6 +1125,10 @@ def handle_or_reraise(context, err) end handler[:handler].call(err, obj, args, context, field) else + if context[:backtrace] || using_backtrace + err = GraphQL::Backtrace::TracedError.new(err, context) + end + raise err end end diff --git a/spec/graphql/schema_spec.rb b/spec/graphql/schema_spec.rb index d8c401c4fc..9fa783c5fe 100644 --- a/spec/graphql/schema_spec.rb +++ b/spec/graphql/schema_spec.rb @@ -560,4 +560,48 @@ class Query < GraphQL::Schema::Object assert schema2.subscription assert schema2.instance_variable_get(:@subscription_extension_added) end + + describe "backtrace error handling" do + class CustomError < RuntimeError; end + class Query < GraphQL::Schema::Object + field :test, Integer, null: false + + def test + raise CustomError + end + end + + it "raises a TracedError when backtrace is enabled" do + schema = Class.new(GraphQL::Schema) do + query(Query) + use GraphQL::Backtrace + end + query_str = '{ test }' + + assert_raises(GraphQL::Backtrace::TracedError) do + schema.execute(query_str) + end + end + + it "rescues them when using rescue_from with backtrace" do + schema = Class.new(GraphQL::Schema) do + query(Query) + use GraphQL::Backtrace + + rescue_from(CustomError) do + raise GraphQL::ExecutionError.new('Handled CustomError') + end + end + query_str = '{ test }' + expected_errors = [ + { + 'message' => 'Handled CustomError', + 'locations' => [{'line' => 1, 'column' => 3}], + 'path' => ['test'] + } + ] + + assert_equal expected_errors, schema.execute(query_str).to_h['errors'] + end + end end