Skip to content

How to correctly propagate errors from plugins? #3626

@borekb

Description

@borekb

I'm writing an Apollo Server plugin that validates a presence of a certain HTTP header. It looks like this:

import { ApolloServerPlugin } from 'apollo-server-plugin-base';
import { OperationDefinitionNode } from 'graphql';

export const myPlugin: ApolloServerPlugin = {
  requestDidStart() {
    return {
      didResolveOperation(context) {
        if (!headerIsValid(context.request.http!.headers.get('x-special-header'))) {
          throw new Error('header not valid');
        }
      },
    };
  },
};

I'm doing that in a plugin because I need access to a parsed query so that I can distinguish introspection queries and normal queries, and I didn't find a better place to do it, see here.

Previously, I had this logic in the context: () => {...} function inside new ApolloServer constructor and when I threw the error there, it was returned to the client and not logged to console.

When I throw an error in a plugin, it is sent to the client but also logged to a console, as if it was an uncaught error.

Am I doing it correctly? Is there a way to avoid having a full stack trace in the server console / logs? My code does not have any error, I just want to indicate a problematic query to the user.

Metadata

Metadata

Assignees

No one assigned

    Labels

    🔌 pluginsRelates to the request pipeline plugin API

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions