如何配置Apollo Client使useMutation仅返回错误message?
如何让Apollo Client的useMutation返回简化的错误信息
可以通过修改errorLink的逻辑,拦截并重构错误对象,让useMutation返回的error仅包含你需要的message。
实现思路
在onError回调中捕获graphQLErrors,提取出目标错误信息后,抛出一个只包含该信息的新错误。后续链路会接收这个简化后的错误,最终useMutation返回的error就是这个新的错误对象,直接取error.message就能拿到清晰的错误文本。
修改后的完整代码示例
import { onError } from '@apollo/client/link/error'; import { HttpLink, from } from '@apollo/client'; import { InMemoryCache, ApolloClient } from '@apollo/client'; import { catchError } from '@apollo/client/utilities'; const errorLink = onError(({ graphQLErrors, operation, forward }) => { if (graphQLErrors) { // 按需处理:提取第一个错误的message,或拼接所有错误信息 const errorMessage = graphQLErrors[0].message; // 抛出简化后的错误,替换原复杂错误结构 return forward(operation).pipe( catchError(() => { throw new Error(errorMessage); }) ); } }); const httpLink = new HttpLink({ uri: 'http://localhost:8000/graphql' }); const appLink = from([errorLink, httpLink]); export const ApolloClientProvider = new ApolloClient({ link: appLink, cache: new InMemoryCache(), });
组件中使用示例
此时useMutation返回的error已简化,直接读取message即可:
const [createUser, { data, loading, error }] = useMutation(CREATE_USER); if (error) { console.log(error.message); // 直接获取清晰的错误提示文本 }
如果需要展示所有错误信息,可将graphQLErrors[0].message替换为graphQLErrors.map(err => err.message).join('; '),实现多错误信息的拼接。
内容的提问来源于stack exchange,提问作者Marius Seba
相关产品推荐
相关产品推荐

