Introduction
Error handling on the client helps you catch and manage problems when fetching or sending data. It keeps your app working smoothly and shows helpful messages to users.
Jump into concepts and practice - no test required
Error handling on the client helps you catch and manage problems when fetching or sending data. It keeps your app working smoothly and shows helpful messages to users.
try { const result = await client.query({ query: YOUR_QUERY }); // use result.data } catch (error) { // handle error here }
try...catch to catch errors from async GraphQL calls.try { const result = await client.query({ query: GET_USERS }); console.log(result.data.users); } catch (error) { console.error('Error fetching users:', error.message); }
then and catch to handle success and errors.client.query({ query: GET_POSTS })
.then(result => console.log(result.data.posts))
.catch(error => console.error('Failed to load posts:', error.message));This program tries to get a list of books from a GraphQL server. If it works, it prints the books. If there is an error, it prints an error message.
import { ApolloClient, InMemoryCache, gql } from '@apollo/client'; const client = new ApolloClient({ uri: 'https://example.com/graphql', cache: new InMemoryCache() }); const GET_BOOKS = gql` query { books { title author } } `; async function fetchBooks() { try { const result = await client.query({ query: GET_BOOKS }); console.log('Books:', result.data.books); } catch (error) { console.error('Error fetching books:', error.message); } } fetchBooks();
Always handle errors to avoid your app crashing unexpectedly.
Show friendly messages to users when errors happen.
Network errors and GraphQL errors are different; handle both.
Error handling keeps your app stable and user-friendly.
Use try...catch or catch on promises to catch errors.
Show clear messages so users know what went wrong.
.then() for success and .catch() for errors..then(...).catch(...). client.query(...).then(...).catch(error => handleError(error)) matches this.client.query({ query: GET_USER })
.then(response => console.log('User:', response.data.user))
.catch(error => console.log('Error:', error.message)).catch() block runs, logging the error message.try {
const response = await client.query({ query: GET_POSTS });
console.log(response.data.posts);
} catch {
console.log('Failed to fetch posts');
}catch { ... } without (error), preventing access to the error details.async function submitData() {
try {
const result = await client.mutate({ mutation: ADD_ITEM, variables: { name: 'Book' } });
console.log('Item added:', result.data.addItem.id);
} catch (error) {
if (error.networkError) {
alert('Network problem, please try again later.');
} else {
alert('An error occurred.');
}
}
}