Error Handling
You can configure your schema to rescue application errors during field resolution. Errors during batch loading will also be rescued.
Thanks to @exAspArk for the graphql-errors gem which inspired this behavior and @thiago-sydow who suggested an implementation like this.
Add error handlers
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:
-
erris the error that was raised during field execution, then rescued -
objis the object which was having a field resolved against it -
argsis the Hash of arguments passed to the resolver -
ctxis the query context -
fieldis theGraphQL::Schema::Fieldinstance for the field where the error was rescued
Inside the handler, you can:
-
Raise a GraphQL-friendly
GraphQL::ExecutionErrorto return to the user -
Re-raise the given
errto crash the query and halt execution. (The error will propagate to your application, eg, the controller.) -
Report some metrics from the error, if applicable
-
Return a new value to be used for the error case (if not raising another error)