Created
April 5, 2017 18:23
-
-
Save tiegz/656b7cf7db9e98d08f01e6f29ad0efe8 to your computer and use it in GitHub Desktop.
RescueInstrumentation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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