How to use apollo-server-errors - 10 common examples

To help you get started, we’ve selected a few apollo-server-errors examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github commercetools / merchant-center-application-kit / graphql-test-utils / create-graphql-mock-server.js View on Github external
schema,
      mocks,
    });
    const { query, variables, operationName } = JSON.parse(req.body());
    const rootValue = getRootValue(operations, operationName, variables);
    let response;
    try {
      response = await graphql({
        schema,
        source: query,
        variableValues: variables,
        rootValue,
      });
    } catch (error) {
      // https://github.com/apollographql/apollo-server/blob/61e69412c0aa88b358a2eef4ba635e8618db9946/packages/apollo-server-core/src/runHttpQuery.ts#L295-L297
      response = { error: formatApolloErrors([error]) };
    }
    return res.status(200).body(JSON.stringify(response));
  };
  const handleProxyGraphQLRequest = async (req, res) => {
github apollographql / apollo-server / packages / apollo-server-core / src / runQuery.ts View on Github external
(): Promise => {
        // Parse the document.
        let documentAST: DocumentNode;
        if (options.parsedQuery) {
          documentAST = options.parsedQuery;
        } else if (!options.queryString) {
          throw new Error('Must supply one of queryString and parsedQuery');
        } else {
          const parsingDidEnd = extensionStack.parsingDidStart({
            queryString: options.queryString,
          });
          let graphqlParseErrors: SyntaxError[] | undefined;
          try {
            documentAST = parse(options.queryString);
          } catch (syntaxError) {
            graphqlParseErrors = formatApolloErrors(
              [
                fromGraphQLError(syntaxError, {
                  errorClass: SyntaxError,
                }),
              ],
              {
                debug,
              },
            );
            return Promise.resolve({ errors: graphqlParseErrors });
          } finally {
            parsingDidEnd(...(graphqlParseErrors || []));
          }
        }

        if (
github apollographql / apollo-server / packages / apollo-server-core / src / runQuery.ts View on Github external
(): Promise => {
        // Parse the document.
        let documentAST: DocumentNode;
        if (options.parsedQuery) {
          documentAST = options.parsedQuery;
        } else if (!options.queryString) {
          throw new Error('Must supply one of queryString and parsedQuery');
        } else {
          const parsingDidEnd = extensionStack.parsingDidStart({
            queryString: options.queryString,
          });
          let graphqlParseErrors: SyntaxError[] | undefined;
          try {
            documentAST = parse(options.queryString);
          } catch (syntaxError) {
            graphqlParseErrors = formatApolloErrors(
              [
                fromGraphQLError(syntaxError, {
                  errorClass: SyntaxError,
                }),
              ],
              {
                debug,
              },
            );
            return Promise.resolve({ errors: graphqlParseErrors });
          } finally {
            parsingDidEnd(...(graphqlParseErrors || []));
          }
        }

        if (
github apollographql / apollo-server / packages / apollo-server-core / src / runHttpQuery.ts View on Github external
persistedQueryRegister,
      };

      return runQuery(params);
    } catch (e) {
      // Populate any HttpQueryError to our handler which should
      // convert it to Http Error.
      if (e.name === 'HttpQueryError') {
        // async function wraps this in a Promise
        throw e;
      }

      // This error will be uncaught, so we need to wrap it and treat it as an
      // internal server error
      return {
        errors: formatApolloErrors([e], optionsObject),
      };
    }
  }) as Array }>>;
github apollographql / apollo-server / packages / apollo-server-core / src / runHttpQuery.ts View on Github external
const defaultHeaders = { 'Content-Type': 'application/json' };
  // force no-cache on PersistedQuery errors
  const headers = hasPersistedQueryError(errors)
    ? {
        ...defaultHeaders,
        'Cache-Control': 'private, no-cache, must-revalidate',
      }
    : defaultHeaders;

  type Result =
   & Pick
   & { errors: E[] | ApolloError[] }

  const result: Result = {
    errors: options
      ? formatApolloErrors(errors, {
          debug: options.debug,
          formatter: options.formatError,
        })
      : errors,
  };

  if (extensions) {
    result.extensions = extensions;
  }

  throw new HttpQueryError(
    statusCode,
    prettyJSONStringify(result),
    true,
    headers,
  );
github apollographql / apollo-server / packages / apollo-server-core / src / runQuery.ts View on Github external
.catch(executionError => {
            return {
              // These errors will get passed through formatApolloErrors in the
              // `then` below.
              // TODO accurate code for this error, which describes this error, which
              // can occur when:
              // * variables incorrectly typed/null when nonnullable
              // * unknown operation/operation name invalid
              // * operation type is unsupported
              // Options: PREPROCESSING_FAILED, GRAPHQL_RUNTIME_CHECK_FAILED

              errors: [fromGraphQLError(executionError)],
            } as ExecutionResult;
          })
          .then(result => {
github apollographql / apollo-server / packages / apollo-server-core / src / runQuery.ts View on Github external
.catch(executionError => {
            return {
              // These errors will get passed through formatApolloErrors in the
              // `then` below.
              // TODO accurate code for this error, which describes this error, which
              // can occur when:
              // * variables incorrectly typed/null when nonnullable
              // * unknown operation/operation name invalid
              // * operation type is unsupported
              // Options: PREPROCESSING_FAILED, GRAPHQL_RUNTIME_CHECK_FAILED

              errors: [fromGraphQLError(executionError)],
            } as ExecutionResult;
          })
          .then(result => {
github apollographql / apollo-server / packages / apollo-server-core / src / runHttpQuery.ts View on Github external
export function throwHttpGraphQLError(
  statusCode: number,
  errors: Array,
  options?: Pick,
  extensions?: GraphQLExecutionResult['extensions'],
): never {
  const defaultHeaders = { 'Content-Type': 'application/json' };
  // force no-cache on PersistedQuery errors
  const headers = hasPersistedQueryError(errors)
    ? {
        ...defaultHeaders,
        'Cache-Control': 'private, no-cache, must-revalidate',
      }
    : defaultHeaders;

  type Result =
   & Pick
   & { errors: E[] | ApolloError[] }

  const result: Result = {
    errors: options
      ? formatApolloErrors(errors, {
          debug: options.debug,
          formatter: options.formatError,
        })
github apollographql / apollo-server / packages / apollo-server-core / src / requestPipeline.ts View on Github external
// PrefixingKeyValueCache yet.
    if (!(persistedQueryCache instanceof PrefixingKeyValueCache)) {
      persistedQueryCache = new PrefixingKeyValueCache(
        persistedQueryCache,
        APQ_CACHE_PREFIX,
      );
    }

    queryHash = extensions.persistedQuery.sha256Hash;

    if (query === undefined) {
      query = await persistedQueryCache.get(queryHash);
      if (query) {
        metrics.persistedQueryHit = true;
      } else {
        throw new PersistedQueryNotFoundError();
      }
    } else {
      const computedQueryHash = computeQueryHash(query);

      if (queryHash !== computedQueryHash) {
        throw new InvalidGraphQLRequestError(
          'provided sha does not match query',
        );
      }

      // We won't write to the persisted query cache until later.
      // Defering the writing gives plugins the ability to "win" from use of
      // the cache, but also have their say in whether or not the cache is
      // written to (by interrupting the request with an error).
      metrics.persistedQueryRegister = true;
    }
github apollographql / apollo-server / packages / apollo-server-core / src / requestPipeline.ts View on Github external
const request = requestContext.request;

  let { query, extensions } = request;

  let queryHash: string;

  let persistedQueryCache: KeyValueCache | undefined;
  metrics.persistedQueryHit = false;
  metrics.persistedQueryRegister = false;

  if (extensions && extensions.persistedQuery) {
    // It looks like we've received a persisted query. Check if we
    // support them.
    if (!config.persistedQueries || !config.persistedQueries.cache) {
      throw new PersistedQueryNotSupportedError();
    } else if (extensions.persistedQuery.version !== 1) {
      throw new InvalidGraphQLRequestError(
        'Unsupported persisted query version',
      );
    }

    // We'll store a reference to the persisted query cache so we can actually
    // do the write at a later point in the request pipeline processing.
    persistedQueryCache = config.persistedQueries.cache;

    // This is a bit hacky, but if `config` came from direct use of the old
    // apollo-server 1.0-style middleware (graphqlExpress etc, not via the
    // ApolloServer class), it won't have been converted to
    // PrefixingKeyValueCache yet.
    if (!(persistedQueryCache instanceof PrefixingKeyValueCache)) {
      persistedQueryCache = new PrefixingKeyValueCache(