Skip to content
This repository was archived by the owner on Mar 20, 2023. It is now read-only.
This repository was archived by the owner on Mar 20, 2023. It is now read-only.

Swallow GraphQL errors by Express #803

Open
@Yoann-Abbes

Description

@Yoann-Abbes

Hi

I'm having issues using a simple express error handler middleware to swallow errors thrown in GraphQL resolvers

For example, I would have:

GQLside

function gqlQuery {
    if (!something) {
      throw new Error('Some Error');
    }

Express side

app.use(
      '/graphql',
     {
      schema,
      context,
      graphiql: true,
      customFormatErrorFn: (error: any) => {
        const errParams = {
          message: error.message,
          locations: error.locations,
          stack: error.stack,
        };
        return errParams;
      },
);

app.use((err, req, res, next) => {
      logger.info('Express middleware error handler')
      res.sendStatus(200)
      next();
    });

What I need, is when inside the resolver I throw the Some Error, Express swallows it inside it's middleware.
It does not work

The only way I managed to do it, is by throwing inside the customFormatErrorFn function:

customFormatErrorFn: (error: any) => {
        const errParams = {
          message: error.message,
          locations: error.locations,
          stack: error.stack,
        };
        if (error.originalError.message.startsWith('Some Error')) {
          throw error;
        }

If I do that, the Express middleware is being called.

But GraphQL returns a bad formatted response

{
  "message": "Unexpected token O in JSON at position 0",
  "stack": "SyntaxError: Unexpected token O in JSON at position 0"
}

I don't understand how I can simply manage GraphQL errors through Express. I'm certainly doing something wrong

My final goal is to catch those errors before they are sent to the client (to chose if I log them for example)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions