【发布时间】:2021-03-18 16:46:43
【问题描述】:
我很难在客户端获取自定义 Apollo 错误。
这是服务器代码:
...
const schema = makeExecutableSchema({
typeDefs: [constraintDirectiveTypeDefs, ...typeDefs],
resolvers,
schemaTransforms: [constraintDirective()],
});
const server = new ApolloServer({
schema,
dataSources,
context({ req }) {
const token = req.headers.authorization;
const user = token ? getUserFromToken(token) : '';
return { user };
},
debug: false,
formatError: (err) => {
// ToDo: Generate unique token and log error
if (err!.extensions!.code == 'INTERNAL_SERVER_ERROR') {
return new ApolloError('We are having some trouble', 'ERROR', {
token: 'uniquetoken',
});
}
return err;
},
uploads: false,
});
...
客户端代码:
...
const ADD_CLAIM = gql`
mutation addClaim($claim: ClaimInput!) {
addClaim(claim: $claim) {
id
}
}
`;
...
const [addClaim, { data, error }] = useMutation(ADD_CLAIM);
...
const onSubmit = async () => {
try {
debugger;
const r = await addClaim({
variables: {
input: {
id: insured.insured,
date: '20/12/2020',
...
therapy: treatment.treatments.map(treat => ({
id: treat.treatId,
...
})),
},
},
});
debugger;
console.log('r', r);
} catch (err) {
debugger;
setFormError(error ? error.message : err.message);
console.log('Error:', err);
}
};
...
if (error) {
debugger;
return <div>error</div>;
}
我希望收到自定义错误:“我们遇到了一些麻烦”。 但是,无论我做什么,我都得到:“响应不成功:收到状态代码 400”
【问题讨论】:
-
正常gql错误为200 ...钩子可以有
onError处理程序,钩子返回error道具(直接使用/生效)...你不需要await/try/catch.. . 将debugger放在“主要组件主体/流程”或onError处理程序中...或使用链接apollographql.com/docs/react/data/error-handling -
我做到了。没用。
标签: javascript graphql apollo-client apollo-server graphql-js