将 ApolloError 传播给客户端

Propagate ApolloError to client

我很难在客户端获得自定义 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% 给出来自服务器的自定义错误:

但我在客户端收到:

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

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

这是我的错误所在:

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 是个讨厌的野兽