Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avalla/e0ea17cda24cc6b6f9f39a69609816d5 to your computer and use it in GitHub Desktop.
Save avalla/e0ea17cda24cc6b6f9f39a69609816d5 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
const CLS_CONTEXT_ATTRIBUTE = 'ctx';
// 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 moleculer'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