Is there a way to return at the same time both error and data in a graphql resolver in Apollo Server?
GraphQL works with both object & field-level resolvers. Partial errors works as long as they’re in different fields. You can still use object resolvers, but they have to be surfaced as different fields, such as Query.user
(and Query.user1/Query.user2
via aliasing) and Query.product
.
For example:
type User {
eyeColor: String
name: String
}
const resolvers = {
User: {
eyeColor: (parent, args, context, info) => {
return "blue";
},
name: (parent, args, context, info) => {
throw new ApolloError("Failed to get user name");
}
}
}
query {
user {
eyeColor
name
}
}
{
"data": {
"user": {
"eyeColor": "blue",
"name": null
}
},
"errors": [
{
"message": "Failed to get user name",
"path": ["user", "name"],
...
}
]
}
Throwing an error and results in 1 resolver does not work (you will only get the error), and if a field that can return an object returns an error, the fields inside that object will not be processed.
query {
user {
bestFriend # user
}
}
```jsonc
{
"data": {
"user": {
"bestFriend": null // notice that no fields were returned, and therefore you should expect that field resolvers were not invoked for the best friend
}
},
"errors": [
{
"message": "oops",
"path": ["user", "bestFriend"]
}
]
}
It is possible (at the time of writing this) to show process both the errors and the “partial data”.
This is described here:
Apollo Docs - Handling operation errors