Ask any question about JavaScript here... and get an instant response.
How do you handle error responses differently when fetching data from a REST API compared to GraphQL in JavaScript?
Asked on Dec 01, 2025
Answer
When handling error responses from REST APIs and GraphQL in JavaScript, the approach differs due to their distinct response structures. REST APIs typically use HTTP status codes, while GraphQL uses a specific "errors" field in the response.
// Fetching data from a REST API
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('There was a problem with the fetch operation:', error));
// Fetching data from a GraphQL API
fetch('https://api.example.com/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: '{ data { id name } }' })
})
.then(response => response.json())
.then(result => {
if (result.errors) {
throw new Error('GraphQL errors: ' + result.errors.map(e => e.message).join(', '));
}
console.log(result.data);
})
.catch(error => console.error('There was a problem with the GraphQL operation:', error));Additional Comment:
- For REST APIs:
- Check the HTTP status code using "response.ok".
- Throw an error if the response is not "ok".
- Handle errors in the "catch" block.
- For GraphQL APIs:
- Always parse the response as JSON.
- Check for an "errors" field in the response.
- Throw an error if "errors" exist, and handle it in the "catch" block.
- Both approaches use "fetch" and handle errors in a "catch" block, but the error detection logic differs.
Recommended Links:
