Class: GraphQL::Schema::RescueMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/schema/rescue_middleware.rb

Overview

  • Store a table of errors & handlers
  • Rescue errors in a middleware chain, then check for a handler
  • If a handler is found, use it & return a ExecutionError
  • If no handler is found, re-raise the error

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRescueMiddleware

Returns a new instance of RescueMiddleware.



11
12
13
# File 'lib/graphql/schema/rescue_middleware.rb', line 11

def initialize
  @rescue_table = {}
end

Instance Attribute Details

#rescue_tableHash (readonly)

Returns {class => proc} pairs for handling errors.

Returns:

  • (Hash)

    {class => proc} pairs for handling errors



10
11
12
# File 'lib/graphql/schema/rescue_middleware.rb', line 10

def rescue_table
  @rescue_table
end

Instance Method Details

#call(*args) ⇒ Object

Implement the requirement for MiddlewareChain



33
34
35
36
37
38
39
# File 'lib/graphql/schema/rescue_middleware.rb', line 33

def call(*args)
  begin
    yield
  rescue StandardError => err
    attempt_rescue(err)
  end
end

#remove_handler(*error_classes) ⇒ Object

Remove the handler for error_classs

Parameters:

  • error_class (Class)

    the error class whose handler should be removed



28
29
30
# File 'lib/graphql/schema/rescue_middleware.rb', line 28

def remove_handler(*error_classes)
  error_classes.map{ |error_class| rescue_table.delete(error_class) }
end

#rescue_from(*error_classes) {|err| ... } ⇒ Object

Examples:

Rescue from not-found by telling the user

MySchema.rescue_from(ActiveRecord::RecordNotFound) { "An item could not be found" }

Parameters:

  • error_classes (Class)

    one or more classes of errors to rescue from

Yields:

  • (err)

    A handler to return a message for these error instances

Yield Parameters:

  • an (Exception)

    error that was rescued

Yield Returns:

  • (String)

    message to put in GraphQL response



22
23
24
# File 'lib/graphql/schema/rescue_middleware.rb', line 22

def rescue_from(*error_classes, &block)
  error_classes.map{ |error_class| rescue_table[error_class] = block }
end