Apollo-server: Context in formatError

Created on 23 Oct 2017  路  7Comments  路  Source: apollographql/apollo-server

Any way to reach the context inside the formatError function? I couldn't find anything about it in the docs.

export const graphQlRoute = graphqlExpress(req => ({
  schema,
  context: {
    user: req.user
  },
  formatError
}))

Most helpful comment

This doesn't seem possible with apollo-server-koa. When logging and reporting errors, I need to get some info from the request in order to create a relation between the errors and the requester.

Has anyone made any progress for this or found workaround that works with the apollo server integrations?

All 7 comments

Any progress on this or a work around?

What is your use case for this?

As a workaround, you should be able to store the context as a local variable inside the closure. Something like:

export const graphQlRoute = graphqlExpress(req => {
  const context = {
    user: req.user
  };
  return {
    schema,
    context,
    formatError(error) {
      // access context here
    }
  }
});

This forces a re-evaluation of the formatError function on each request - kinda pointless.
I think you can define it outside of the request handler and still get access to the outer closure variables.

BTW, how can you get the variables? Part of the err.source.body?

This doesn't seem possible with apollo-server-koa. When logging and reporting errors, I need to get some info from the request in order to create a relation between the errors and the requester.

Has anyone made any progress for this or found workaround that works with the apollo server integrations?

Needs this aswell.

@martijnwalraven An example use case for this is if you have a custom logger object that you attach to the context, you may want to be able to reference that logger in the formatError() body.

For anyone encountering this issue still, the formatError on Apollo Server today is a hoisting of the principle/pattern behind the underlying formatError in graphql-js, which doesn't have a notion of context supplied to it. For those needing to react to things on the context (which makes a lot of sense!), you might consider using the plugins API's didEncounterErrors or willSendResponse life-cycle hooks, both of which receive context. And for the custom logger use-case above, they _also_ receive the logger that is passed into the ApolloServer constructor, if you've provided one (but that defaults to console, if you haven't).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jpcbarros picture jpcbarros  路  3Comments

veeramarni picture veeramarni  路  3Comments

manuelfink picture manuelfink  路  3Comments

stevezau picture stevezau  路  3Comments

nevyn-lookback picture nevyn-lookback  路  3Comments