Custom Error Object with Apollo Server

I’m trying to use a custom error with apollo-server and it seems that my custom error has a property (code) that isn’t available from within formatError.

import ExtendableError from 'es6-error'

export default class MyError extends ExtendableError {
  constructor(args) {
    let code = Object.keys(args)[0]
    let message = Object.values(args)[0]
    this.code = code

I have a simple error handler works something like this:

let INVALIDREQUEST = 'invalid request'
let e = new MyError({INVALIDREQUEST})
console.log(e.code) // => "INVALIDREQUEST"

I’m having trouble because when I log error.code from within formatError it’s not available.

formatError: function (error) {
  console.log(error.code) // => undefined
  return error

How can I propagate custom properties (like code) of error from within formatError?


Because Apollo Server uses GraphQL.js, we can find the solution by digging deep there:

Essentially, the GraphQL.js reference implementation catches any errors in your resolvers, and delivers them to the formatError function, but it wraps them in a special GraphQL-specific error object, with properties like path, positions, and source.

You can find the original error you threw from the resolver on the originalError field of the error object in formatError, like so:

formatError: function (error) {
  return error

Source: stackoverflow