Sha256: 33eef6f6c877d15645e0560a796fa78b4a90727ee366050a63a7596b680f0bf1

Contents?: true

Size: 1.55 KB

Versions: 6

Compression:

Stored size: 1.55 KB

Contents

# frozen_string_literal: true

module GraphQL
  module Execution
    # A tracer that wraps query execution with error handling.
    # Supports class-based schemas and the new {Interpreter} runtime only.
    #
    # @example Handling ActiveRecord::NotFound
    #
    #   class MySchema < GraphQL::Schema
    #     use GraphQL::Execution::Errors
    #
    #     rescue_from(ActiveRecord::NotFound) do |err, obj, args, ctx, field|
    #       ErrorTracker.log("Not Found: #{err.message}")
    #       nil
    #     end
    #   end
    #
    class Errors
      def self.use(schema)
        schema_class = schema.is_a?(Class) ? schema : schema.target.class
        schema.tracer(self.new(schema_class))
      end

      def initialize(schema)
        @schema = schema
      end

      def trace(event, data)
        case event
        when "execute_field", "execute_field_lazy"
          with_error_handling(data) { yield }
        else
          yield
        end
      end

      private

      def with_error_handling(trace_data)
        yield
      rescue StandardError => err
        rescues = @schema.rescues
        _err_class, handler = rescues.find { |err_class, handler| err.is_a?(err_class) }
        if handler
          obj = trace_data[:object]
          args = trace_data[:arguments]
          ctx = trace_data[:query].context
          field = trace_data[:field]
          if obj.is_a?(GraphQL::Schema::Object)
            obj = obj.object
          end
          handler.call(err, obj, args, ctx, field)
        else
          raise err
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
graphql-1.9.16 lib/graphql/execution/errors.rb
graphql-1.9.15 lib/graphql/execution/errors.rb
graphql-1.9.14 lib/graphql/execution/errors.rb
graphql-1.10.0.pre1 lib/graphql/execution/errors.rb
graphql-1.9.13 lib/graphql/execution/errors.rb
graphql-1.9.12 lib/graphql/execution/errors.rb