【问题标题】:How to send an error message from the apollo- server如何从 apollo 服务器发送错误消息
【发布时间】:2023-03-29 16:28:01
【问题描述】:

这是我的代码

在 apollo 客户端中,我使用 useMutation。

阿波罗客户

  const [addTodo, { loading, error, data }] = useMutation(gql);

阿波罗服务器

 Mutation: {
    signUp: async (_, formSignUp, { models: { User }, res }) => {
      try {
        const user = new User(formSignUp);
        await user.save();
        const token = await user.generateAuthToken();
        res.cookie("darkAmasia", token, {
          httpOnly: true
        });
        return "string";
      } catch (error) {
        ?????????
      }
    }
  }

我应该在 catch 中写什么?发送消息{status:400,error:true}in useMutation 错误。 听说throw new ApolloError是用来做这些的,但是不知道怎么弄。

【问题讨论】:

    标签: node.js graphql react-apollo apollo-client apollo-server


    【解决方案1】:

    阅读更多关于错误处理的信息here

    您可以创建自己的 Error 类来扩展 ApolloError 并将状态作为默认属性传递。

        Mutation: {
        signUp: async (_, formSignUp, { models: { User }, res }) => {
          try {
            const user = new User(formSignUp);
            await user.save();
            const token = await user.generateAuthToken();
            res.cookie("darkAmasia", token, {
              httpOnly: true
            });
            return "string";
          } catch (error) {
            throw new ApolloError("Something went wrong", "BAD_INPUT",{status:400,error:true});
          }
        }
      }
    

    【讨论】:

    • 为什么我在控制台中收到错误消息?如何使这种情况不发生? Uncaught (in promise) Error: GraphQL error: Backend request failed
    • 使用 return 而不是 throw 尝试
    • 不,这也没有帮助。
    猜你喜欢
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    相关资源
    最近更新 更多