Skip to content

Instantly share code, notes, and snippets.

@tiegz
Created April 5, 2017 18:23
Show Gist options
  • Save tiegz/656b7cf7db9e98d08f01e6f29ad0efe8 to your computer and use it in GitHub Desktop.
Save tiegz/656b7cf7db9e98d08f01e6f29ad0efe8 to your computer and use it in GitHub Desktop.
RescueInstrumentation
# This piggy-backs off RescueMiddleware by using the same exception handling
# rules you've defined using rescue_from(), and applying them to lazy fields
# (which would otherwise run after middleware has been run).
# Add this to your schema:
#
# instrument(:field, RescueInstrumentation.new)
#
class RescueInstrumentation
def instrument(type, field)
old_lazy_resolve_proc = field.lazy_resolve_proc
new_lazy_resolve_proc = ->(obj, args, ctx) {
resolved = begin
old_lazy_resolve_proc.call(obj, args, ctx)
rescue StandardError => err
attempt_rescue(err)
end
resolved
}
field.redefine do
lazy_resolve(new_lazy_resolve_proc)
end
end
private def attempt_rescue(err)
handler = GraphSchema.send(:rescue_middleware).rescue_table[err.class]
if handler
message = handler.call(err)
GraphQL::ExecutionError.new(message)
else
raise(err)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment