I have some confusions regarding how graphql handles validation errors and exception messages.
I have gone through
https://github.com/rmosolgo/graphql-ruby/blob/master/guides/queries/error_handling.md
I want to go with the second approach i.e Add errors to the response's "errors" key
But my question is , with GraphQL::ExecutionError is it possible to return json formatted validation error messages? (Form field error messages) Or we can only return String messages as mentioned on the doc? If not then what's the alternative?
`user= User.new(inputs.to_h)
if user.save
{ user: user}
else
GraphQL::ExecutionError.new("Invalid input: #{user.errors.full_messages.join(", ")}")
end`
In this case, I get all the user validation error messages in one single string, but i want in a json format.
@dkumar431 you can use the options parameter when creating a GraphQL::ExecutionError to provide a set of optional fields.
for example:
err = { field: "fluffy", field2: "fluffier" }
return GraphQL::ExecutionError.new("some message", options: err)
does this help?
Thanks for your suggestion. Looks like this is want i needed.
But as GraphQL::ExecutionError returns error with 200 ok but my frondend dev want errors with different 4xx and 5xx status codes. So i end creating up creating a custom error class and throwing the same from elseblock.
@dkumar431 would you mind sharing your Error class please?
@dkumar431 GraphQL is not meant to be used that way. It doesn't even care about the transport (in this case HTTP).
You should always return a status 200 and you might even have success and errors in a single query.
I found this gem graphql-errors and it currently works --> https://github.com/exAspArk/graphql-errors
To match the way graphql-ruby exports errors for, say, required fields that are not filled, you can construct an error like:
raise GraphQL::ExecutionError.new('Validation Failed', options: {
extensions: {
problems: [{ path: ['firstName'], explanation: 'This is because foo' }]
}
})
The spec includes an "extensions" key which may be populated this way:
https://graphql-ruby.org/errors/execution_errors.html#customizing-error-json
There's also a new general-purpose error handling system here: https://graphql-ruby.org/errors/error_handling.html
Please open a new issue if you have trouble with either of those!
I noticed if you return GraphQL::ExecutionError.new in a resolver on the server, then an exception will be raised on the front end (when using Apollo) so you have to wrap the mutation call site in a try/catch.
Most helpful comment
@dkumar431 you can use the
optionsparameter when creating a GraphQL::ExecutionError to provide a set of optional fields.for example:
does this help?