You can configure your schema to rescue application errors during field resolution. Errors during batch loading will also be rescued.
Note: This feature is for class-based schemas using the interpreter runtime%20only.%20For%20%60.define%60-based%20schemas,%20use%20%5BexAspArk/graphql-errors%5D(https://github.com/exaspark/graphql-errors) instead.
Thanks to [@exAspArk
] for the graphql-errors
gem which inspired this behavior and @thiago-sydow
who suggested and implementation like this.
Add error handling to your schema with use GraphQL::Execution::Errors
. (This will be the default in a future graphql-ruby version.)
class MySchema < GraphQL::Schema
# Use the new runtime & analyzers:
use GraphQL::Execution::Interpreter
use GraphQL::Analysis::AST
# Also use the new error handling:
use GraphQL::Execution::Errors
end
Handlers are added with rescue_from
configurations in the schema:
class MySchema < GraphQL::Schema
# ...
rescue_from(ActiveRecord::RecordNotFound) do |err, obj, args, ctx, field|
# Raise a graphql-friendly error with a custom message
raise GraphQL::ExecutionError, "#{field.type.unwrap.graphql_name} not found"
end
rescue_from(SearchIndex::UnavailableError) do |err, obj, args, ctx, field|
# Log the error
Bugsnag.notify(err)
# replace it with nil
nil
end
end
The handler is called with several arguments:
err
is the error that was raised during field execution, then rescuedobj
is the object which was having a field resolved against itargs
is the the Hash of arguments passed to the resolverctx
is the query contextfield
is the GraphQL::Schema::Field
instance for the field where the error was rescuedInside the handler, you can:
GraphQL::ExecutionError
to return to the usererr
to crash the query and halt execution. (The error will propagate to your application, eg, the controller.)