If a resolver gets a user from a database for example and no user was not found, should an error be thrown? What is best practice for no data found?
On GraphQL errorsThe onError link can retry a failed operation based on the type of GraphQL error that's returned. For example, when using token-based authentication, you might want to automatically handle re-authentication when the token expires. // instead of the onError link. This just logs the error.
To add errors to your data, you need to use the Union type (a.k.a. Result ) in your GraphQL schema. Also, the logic in the resolver is rewritten so that next to the result or error for the operation you also need to return a type for it.
If the request fails or partially fails (e.g. because the user requesting the data doesn't have the right access permissions), a second root field called "errors" is added to the response: { "data": { ... }, "errors": [ ... ] } For more details, you can refer to the GraphQL specification.
The standard error handling mechanism from GraphQL with return a JSON containing: a data key which contains the data corresponding to the GraphQL operation (query, mutation, subscription) invoked and. an errors key which contains an array of errors returned by the server, with a message and location.
There's a case to be made for simply returning null
, rather than throwing an error, particularly in this scenario. The errors
part of your response will includes two general types of errors:
In both of these cases, something bad and unexpected happened server-side. As a client, I need to maybe file a defect, open an issue or go yell at somebody 3 cubicles over. But the point is, these errors shouldn't occur in the normal course of things.
On the other hand, let's consider looking up a user by their username or some other identifier. Rather than a search that returns an array of users, let's assume we're using an exact match and only returning a single user.
type Query {
user(username: String!): User
}
In a scenario like this, not finding a matching user in the database some of the time is probably expected. As long as the field is nullable, the client will know to expect either a User or null, and can handle either scenario just fine.
If we throw an error, the field will still return null, but now we'll also see an error in our errors
array. The client will now have to do additional work to determine if the error occurred because there was no user found, or if something else went wrong (after all, if a server error occurred, we may need to take additional action, for example alerting the user to the fact). Moreover, our errors
array is no longer an indicator of response "health", since it may include errors that are being thrown as part of our regular business logic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With