Skip to content

Instantly share code, notes, and snippets.

@mdlavin
Last active January 19, 2022 18:50
Show Gist options
  • Save mdlavin/4e7dffd5786341cb807f9add897b26fa to your computer and use it in GitHub Desktop.
Save mdlavin/4e7dffd5786341cb807f9add897b26fa 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;
}
@dobrynin
Copy link

Minor comment but you've got an invalid semicolon on line 21.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment