1

I have a resolver that is called from execute (graphql package), and when the backend needs to report an error it throws an internal type (AuthError, etc.) that includes an error code that the front-end depends on to respond accordingly. However, I have run into an issue where the result from execute is wrapping this error in a GraphQLError, which includes the original error as originalError, but this portion is not getting propagated up to the client.

Here is the Server Side after the error is thrown and before sending the result to the client: (I am using sockets.)

enter image description here

And here is the client side of this:

enter image description here

So, my question is how can I get this code in the client error? I assume there must be a way to set this extraInfo that the client side has, but I do not see anything in the docs.

Dallas
  • 888
  • 3
  • 10
  • 24

1 Answers1

-3

For future reference ;) in the following article, it's explained how to use the formatError function of GraphQL. You can add the originalError.code or add any other extra info to the error returned to the client this way.

https://codeburst.io/custom-errors-and-error-reporting-in-graphql-bbd398272aeb

In this article the solution is coded for express-graphql, but other libraries have a similar approach:

  import express from 'express'
  import graphql from 'express-graphql'
  import schema from './schema'
  import Context from './Context'

  const app = express()

  app.use('/graphql', graphql(req => ({
    schema,
    context: new Context(req),
    formatError(err) {
      return {
        message: err.message,
        code: err.originalError && err.originalError.code, // <-- The trick is here
        locations: err.locations,
        path: err.path
      }
    }
  })))

Update

For Apollo Server v4 you can see how to handle errors here: https://www.apollographql.com/docs/apollo-server/data/errors

The customer error section https://www.apollographql.com/docs/apollo-server/data/errors#custom-errors shows how to throw a custom error that can be handled by GraphQL

import { GraphQLError } from 'graphql';

throw new GraphQLError(message, {
    extensions: { code: 'YOUR_ERROR_CODE', myCustomExtensions },
});

Check for a more complete example in the section Including custom error details https://www.apollographql.com/docs/apollo-server/data/errors#including-custom-error-details

tiomno
  • 2,178
  • 26
  • 31
  • Can those giving this answer a -1 share if they tried it and it didn't work? What's the problem you found? Can you share your approach in another answer? – tiomno Feb 06 '23 at 10:46
  • Found another question with the same solution https://stackoverflow.com/questions/40124494/custom-error-object-with-apollo-server for those interested. I'd not use a feature that's not documented, so better to check out the update I left in the answer. :) – tiomno Feb 06 '23 at 11:07