【问题标题】:How to add a string to the "error array"?如何将字符串添加到“错误数组”?
【发布时间】:2020-01-09 12:23:49
【问题描述】:

我是graphql的新手。我使用Node.js apollo-server。当我重置错误时,对象被添加到错误数组中。但是如何添加字符串而不是对象?。

示例

throw Error("error")

{"errors":["error]}

【问题讨论】:

    标签: node.js graphql apollo-server


    【解决方案1】:

    您可以使用docs 中的formatError。

    格式化从服务器返回的错误和响应的函数,以及graphql执行的参数(runQuery)

    例如

    server.ts

    import { ApolloServer, gql } from 'apollo-server';
    import { GraphQLError } from 'graphql';
    
    const typeDefs = gql`
      type Query {
        _: Boolean
      }
    `;
    const resolvers = {
      Query: {
        _: () => {
          throw new Error('error');
        },
      },
    };
    const server = new ApolloServer({
      typeDefs,
      resolvers,
      formatError(error: GraphQLError) {
        return error.message as any;
      },
    });
    
    server.listen().then(({ url }) => {
      console.log(`Apollo server is listening on ${url}`);
    });
    

    客户端的 GraphQL 查询:

    query {
      _ 
    }
    

    回应:

    {
      "errors": [
        "error"
      ],
      "data": {
        "_": null
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 2022-01-12
      相关资源
      最近更新 更多