Handling errors that happen outside of AppSchema is challenging, because the error handling logic is so dependent on the query
To clients, no matter where the error happens, they should receive a standard JSON response describing the error.
Problem:
With GraphQL-ruby, errors that happen within are relayed in a different format than errors that occur outside of the stack. This makes clients needing to understand multiple error formats.
Consider this case:
class GraphqlController < ApplicationController
def execute
############################
raise "Random Failure!"
############################
variables = ensure_hash(params[:variables])
query = params[:query]
operation_name = params[:operationName]
context = {
# Query context goes here, for example:
current_profile: current_profile,
request: request
}
result = AppSchema.execute(query, variables: variables, context: context, operation_name: operation_name)
render json: result
end
rescue_from StandardError do |e|
render json: {error: e.message}, status: 500
end
the rescue_from would not deliver the correct error response and I don't see an GraphQL api for translating a exception into a graphql compliant error.
Another case is auth failures.
Typically it seems that authentication is handled outside of GraphQL. If we want to deliver a GraphQL-like authentication error when authentication fails, then there is not a very clean way to do it.
Ask:
How can I make errors that happen outside of GraphQL-ruby look like errors that happen within GraphQL-ruby?
Same here, we have error, but app thinks it success and move forward after unsucessfull purchapse
I know this is old but if anyone else ends up here, there are some errors in the example. If you want graphql clients to handled the standardized error handling, the server needs to always respond with 200 status code, not 500 (or anything else). The error messages should also be an array named errors, not error.
# graphql_controller.rb
rescue_from StandardError do |e|
# INCORRECT
render json: { error: e.message }, status: 500 # incorrect, will throw client error
# CORRECT
render json: { errors: [{ message: e.message }] } # correctly handled by graphql clients
end
Thanks for sharing your solution here, @bbugh!
I don't plan to do more on this, but if anyone wants to upstream this improvement to the graphql:install generator, you'll find the GraphqlController template here:
It has a little bit of error handling for _development_ already, so maybe that could be improved along these lines:
Most helpful comment
I know this is old but if anyone else ends up here, there are some errors in the example. If you want graphql clients to handled the standardized error handling, the server needs to always respond with
200status code, not500(or anything else). The error messages should also be an array namederrors, noterror.