onError 导入未在 Apollo 中使用
Posted
技术标签:
【中文标题】onError 导入未在 Apollo 中使用【英文标题】:onError Import not being used in Apollo 【发布时间】:2021-05-28 20:38:54 【问题描述】:我正在尝试使用 Apollo 和 Graphql 处理我的 React Native with Expo 应用程序上的错误。
问题是,在我的 apolloServices.js 中,我正在尝试使用 onError
函数,尽管我尝试了 apollo-link-error
和 @apollo/client/link/error
导入仍然是灰色的。它在 ApolloClient 的函数。
反应原生:0.63.2 @阿波罗客户端:3.3.11 阿波罗链接错误:1.1.13
// Apollo resources
import HttpLink from 'apollo-link-http';
import ApolloClient from '@apollo/client'; // Tried putting onError here
import onError from 'apollo-link-error'; // And here
//import onError from '@apollo/client/link/error'; // Also here
import
InMemoryCache,
defaultDataIdFromObject,
from 'apollo-cache-inmemory';
import setContext from 'apollo-link-context';
/* Constants */
import KEY_TOKEN from '../constants/constants';
/**
* @name ApolloServices
* @description
* The Apollo Client's instance. App.js uses it to connect to graphql
* @constant httpLink HttpLink Object. The url to connect the graphql
* @constant defaultOPtions Object. Default options for connection
* @constant authLink
*/
const httpLink = new HttpLink(
uri: 'workingUri.com',
);
const defaultOptions =
watchQuery:
fetchPolicy: 'no-cache',
errorPolicy: 'ignore',
,
query:
fetchPolicy: 'no-cache',
errorPolicy: 'all',
,
;
//Create link with auth header
const authLink = setContext((_, headers ) =>
// get the authentication token from local storage if it exists
return AsyncStorage?.getItem(KEY_TOKEN).then((token) =>
// return the headers to the context so httpLink can read them
return
headers:
...headers,
'auth-token': token ? token : '',
,
;
);
);
export default new ApolloClient(
/* ON ERROR FUNCTION HERE*/
onError: (graphQLErrors, networkError) =>
if (graphQLErrors)
graphQLErrors.map(
( message, locations, path ) =>
console.log(
`[GraphQL error]: Message: $message, Location: $locations, Path: $path`,
),
);
if (networkError)
console.log(`[Network error]: $networkError`);
,
cache: new InMemoryCache(),
defaultOptions: defaultOptions,
link: authLink.concat(httpLink),
request: (operation) =>
operation.setContext(
headers:
'auth-token': token ? token : '',
,
);
,
);
除此之外,该应用程序运行良好,我想要的只是处理 graphql 和网络错误
【问题讨论】:
【参考方案1】:最好的解决方案是使用这种方法
const errorControl = onError(( networkError, graphQLErrors ) =>
if (graphQLErrors)
graphQLErrors.map(( message, locations, path ) =>
console.log(
" [GraphQL error]: Message", message, ", Location: ", locations, ", Path: ", path)
);
if (networkError)
console.log(" [Network error]:", networkError)
;
);
export default new ApolloClient(
cache: new InMemoryCache(),
defaultOptions: defaultOptions,
link: errorControl.concat(authLink.concat(httpLink)),
headers:
authorization: token ? token : '',
,
);
【讨论】:
谢谢!我设法以另一种方式做到了(但做起来和实施都不是那么容易,因为不是这种方式,所以我没有在这里发布)以上是关于onError 导入未在 Apollo 中使用的主要内容,如果未能解决你的问题,请参考以下文章
在 Apollo React 的 onError 中读取响应标头
如何防止我的 Apollo 客户端错误处理程序(onError,错误链接)因同一错误被调用两次?
apollo-client, onError, ApolloProvider, client.writeData(localstate)... 当服务器返回 401 时如何处理对用户的身份验证