这种情况通常发生在GraphQL查询中涉及多个字段时。当其中一个字段出现错误时,整个查询将失败并返回错误。为了避免这个问题,可以使用GraphQL中的错误处理机制。以下是一个示例:
const { ApolloServer, gql, ApolloError } = require('apollo-server');
const typeDefs = gql`
type Query {
books: [Book]
}
type Book {
id: ID!
title: String!
author: String!
}
`;
const books = [
{
id: '1',
title: 'Harry Potter and the Sorcerer\'s Stone',
author: 'J.K. Rowling'
},
{
id: '2',
title: 'The Hitchhiker\'s Guide to the Galaxy',
author: 'Douglas Adams'
},
];
const resolvers = {
Query: {
books: () => {
try {
// Try to fetch data from a remote API or database
// If successful, return the data
return books;
} catch (error) {
// If there is an error, throw an ApolloError
throw new ApolloError('Failed to fetch books', 'DATA_SOURCE_ERROR');
}
}
}
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`� Server ready at ${url}`);
});
在这个示例中,当尝试从远程API或数据库获取数据时,如果出现错误,就会抛出一个ApolloError。这个错误会被GraphQL捕获并将其作为返回结果的一部分返回。这使得客户端能够在收到部分数据的同时得到关于错误的信息,从而更好地处理这种情况。