【问题标题】:Propagate ApolloError to client将 ApolloError 传播给客户端
【发布时间】: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”

我 100% 从服务器给出自定义错误:

但我在客户端收到:

此外,当我检查开发人员工具的网络选项卡时,响应我确实有我的错误:

但我无法从代码中访问它。 顺便说一句,在操场上我看到了我的错误:

【问题讨论】:

  • 正常gql错误为200 ...钩子可以有onError处理程序,钩子返回error道具(直接使用/生效)...你不需要await/try/catch .. . 将debugger 放在“主要组件主体/流程”或onError 处理程序中...或使用链接apollographql.com/docs/react/data/error-handling
  • 我做到了。没用。

标签: javascript graphql apollo-client apollo-server graphql-js


【解决方案1】:

我的错误在哪里:

error.networkError.result.errors

什么没人知道?

或者

const errorLink = onError(({ graphQLErrors, networkError }) => {
  debugger;
  console.log(graphQLErrors);
  console.log(networkError);
});

const client = new ApolloClient({
  ...
  link: ApolloLink.from( [errorLink, ...]),    
});

它也有效。

是的,有时 GraphQL 是一头讨厌的野兽

【讨论】:

    猜你喜欢
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 2019-03-16
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多