exceptionerror-handlinggraphqlapollo-server

Can't use extensions with GraphQLError


From the Apollo Graphql document, this way can define extension error:

https://www.apollographql.com/docs/apollo-server/data/errors/

    import { GraphQLError } from 'graphql';

    throw new GraphQLError('the error message', 
      extensions: {
        code: 'SOMETHING_BAD_HAPPENED',
        http: {
          status: 404,
          headers: new Map([
            ['some-header', 'it was bad'],
            ['another-header', 'seriously'],
          ]),
        },
      },
    );

But in my case it got this error:

Argument of type '{ extensions: { code: string; http: { status: number; headers: Map<string, string>; }; }; }' is not assignable to parameter of type 'Maybe<ASTNode | readonly ASTNode[]>'.
  Object literal may only specify known properties, and 'extensions' does not exist in type 'ASTNode | readonly ASTNode[]'.

 23         extensions: {
            ~~~~~~~~~~~~~
 24           code: 'SOMETHING_BAD_HAPPENED',
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...
 31           },
    ~~~~~~~~~~~~
 32         },
    ~~~~~~~~~

Found 1 error(s).

I'm using these packages:

I also tried to install apollo-server-testing but still can't use extensions.


Solution

  • You forgot to encapsulate the second argument with an object. { extensions }

    Do this:

    throw new GraphQLError('the error message', 
    { // curly bracket here to open the object
      extensions: {
        code: 'SOMETHING_BAD_HAPPENED',
        http: {
          status: 404,
          headers: new Map([
            ['some-header', 'it was bad'],
            ['another-header', 'seriously'],
          ]),
        },
      },
    } // curly bracket here to close the object
    );
    

    Also, @Alpin Cleopatra answer works because of the constructor overload, but it's not intended to be used this way.

    See the two signatures here: enter image description here