我喜欢apollo-angular文档中建议的全局设置。我不确定是否应该将errorLink放在选项中,或者是否应该将它与httpLink组合在一起。
最大的问题是:我如何在我的代码中使用它?我在任何地方都找不到示例,也不知道如何开始。我的脑海中还没有阿波罗链接错误的概念。
app.module.ts
...
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { onError } from 'apollo-link-error';
// This is just a copy and past from the docs at this time.
const errorLink = 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}`);
});
@NgModule({
imports: [
...
],
declarations: [
...
],
providers: [
...
{ provide: APOLLO_OPTIONS,
useFactory: (httpLink: HttpLink) => {
return {
cache: new InMemoryCache(),
link: httpLink.create({
uri: 'http://localhost:3000/graphql',
}),
options: {
errorLink
},
defaultOptions: {
}
};
},
deps: [HttpLink]
},
],
})
export class AppModule { }带有查询的组件:
this.apollo
.watchQuery({
query: getAllMembers,
})
.valueChanges
.subscribe(result => {
if (result !== null) {
this.dataSource.data = result.data['getMembers'];
} else {
// What should be here??? This doesn't seem to work.
console.log('errors ', result.errors);
}
});发布于 2020-01-17 23:00:42
我也有同样的问题。Apollo-link-error就像一个中间件,您可以使用它在代码中的单个位置截取错误,并对其进行一些通用的错误处理。如果您希望将错误传播到服务或组件,则有一个额外的步骤:我注意到错误详细信息将从响应中删除,除非您使用:
apollo.watchQuery({
..., // options
errorPolicy: 'all'
});这样,您就可以检查服务上的响应,并查找“数据”和“错误”。如果它是一个验证错误,那么它就是一个带有errors对象的http 200。然后,您可以将该错误传播到组件,并将其用于在表单上显示错误消息。
有关详细信息,请访问:
https://www.apollographql.com/docs/react/data/error-handling/ https://www.apollographql.com/docs/angular/features/error-handling/#error-policies
希望它能帮上忙!
https://stackoverflow.com/questions/57500906
复制相似问题