0
0
GraphQLquery~5 mins

Error handling on client in GraphQL

Choose your learning style9 modes available
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.

When a query fails because the server is down.
When the user sends wrong or incomplete data in a mutation.
When the network connection is lost during a request.
When the server returns an error message for a query.
When you want to show loading and error states in your app.
Syntax
GraphQL
try {
  const result = await client.query({ query: YOUR_QUERY });
  // use result.data
} catch (error) {
  // handle error here
}
Use try...catch to catch errors from async GraphQL calls.
Errors can come from network issues or server responses.
Examples
This example tries to get users and logs them. If it fails, it logs an error message.
GraphQL
try {
  const result = await client.query({ query: GET_USERS });
  console.log(result.data.users);
} catch (error) {
  console.error('Error fetching users:', error.message);
}
This uses promises with then and catch to handle success and errors.
GraphQL
client.query({ query: GET_POSTS })
  .then(result => console.log(result.data.posts))
  .catch(error => console.error('Failed to load posts:', error.message));
Sample Program

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.

GraphQL
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();
OutputSuccess
Important Notes

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.

Summary

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.