GraphQL - How to react with different status code?
I am having problems with Graphql and Apollo Client.
I have always created different answers like 401 code when I use REST, but here I don't know how I should make this behavior.
When I get the answer, I want it to go to the catch function. I have this code in the front:
client.query({
query: gql`
query TodoApp {
todos {
id
text
completed
}
}
`,
})
.then(data => console.log(data))
.catch(error => console.error(error));
Can anyone help me?
source to share
The way to return errors in GraphQL (at least in graphql-js) is to throw errors inside resolution functions. Since HTTP status codes are specific to the HTTP transport and GraphQL doesn't care about the transport, there is no way to set a status code there. Instead, you can specify a specific error inside your resolution function:
age: (person, args) => {
try {
return fetchAge(person.id);
} catch (e) {
throw new Error("Could not connect to age service");
}
}
GraphQL errors are sent back to the client like this:
{
"data": {
"name": "John",
"age": null
},
"errors": [
{ "message": "Could not connect to age service" }
]
}
If the message is not enough information, you can create a custom error class for your GraphQL server that contains the status code. To make sure the status code is included in your answer, you need to specify the function formatError
when building the middleware:
app.use('/graphql', bodyParser.json(), graphqlExpress({
schema: myGraphQLSchema,
formatError: (err) => ({ message: err.message, status: err.status }),
}));
source to share
An error message was recently added to the spec :
GraphQL Services can provide additional error reporting with key extensions . This entry, if set, must have a map as its value. This entry is reserved for developers to add additional error information as they see fit, and there are no further restrictions on its content.
Now, using the field extensions
, you can customize the machine-readable information for your records errors
:
{
"errors": [
{
"message": "Name for character with ID 1002 could not be fetched.",
"locations": [ { "line": 6, "column": 7 } ],
"path": [ "hero", "heroFriends", 1, "name" ],
"extensions": {
"code": "CAN_NOT_FETCH_BY_ID",
"timestamp": "Fri Feb 9 14:33:09 UTC 2018"
}
}
]
}
The latest version of Apollo-Server is compliant with the specification for this feature. Check here .
source to share