Studio Service

Error Handling

Error handling

Unlike a REST API, GraphQL returns HTTP status code 200 in most cases whether a request fails or succeeds. If you are treating GraphQL queries as traditional HTTP requests, then your HTTP client may not throw an error properly.

It's better to check that the errors field returned with the response body exists.

Example

query {
currentUser {
status
}
}

If the GraphQL query above is called, and an error occurs, then the error response would look like this.

{
"data": {
"currentUser": null
},
"errors": [
{
"message": "An error message"
}
]
}

So, if an HTTP client such as axios is used to consume a GraphQL query, then the client should check for errors for an error message as the example code below.

try {
const response = await axios({
url: "https://graphql.staging.eu.next.sc/graphql",
method: 'POST',
data: {
query: `
query {
currentUser {
userType
status
}
}`
},
headers: {
authorization: 'Bearer Token YOUR_TOKEN_HERE'
}
})
if (response.data.data) {
// Success!! We got the user's status
console.log('success', response.data.data.currentUser.status)
}
if (response.data.errors) {
// Error handling
console.error(response.data.errors[0].message)
}
} catch(e) {
// Handle 5XX status code
}