Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save trmaphi/fb6ae45be291a18da90280e81bcd80be to your computer and use it in GitHub Desktop.
Save trmaphi/fb6ae45be291a18da90280e81bcd80be to your computer and use it in GitHub Desktop.
An Apollo Server formatError function that avoids "Converting circular structure to JSON" errors
// This is the attribute that continuation local storage uses to hold onto
// the current context. The value comes from https://github.com/othiym23/node-continuation-local-storage/blob/fc770288979f6050e4371c1e1b44d2b76b233664/context.js#L11
const CLS_CONTEXT_ATTRIBUTE = 'error@context';
// A formatError function that can be used with
// https://www.apollographql.com/docs/apollo-server/features/errors#for-the-client-response
function formatError (err) {
// The continuation-local-storage module attaches a context attribute to
// errors so that the context can be resolved from errors. The attribute
// is enumerable by default and so it gets included in GraphQL error
// reporing. That alone would not be a problem, but AWS X-Ray's context
// holds a reference to the error leading to an object with circular
// references. Apollo Server does not handle circular references
// gracefully: https://github.com/apollographql/apollo-server/issues/1433
// This workaround marks the CLS context as not enumerable, which means
// not serialized by JSON.stringify(), which means is will not trigger the
// Apollo bug
const originalException = err.extensions && err.extensions.exception;
if (originalException && CLS_CONTEXT_ATTRIBUTE in originalException) {
Object.defineProperty(originalException, CLS_CONTEXT_ATTRIBUTE, {
enumerable: false;
});
}
return err;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment