Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
    super(message)
    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?

like image 669
ThomasReggi Avatar asked Oct 19 '16 07:10

ThomasReggi


2 Answers

With Apollo, you can easily multiplex the errors array in the graphql response for both graphql errors AND custom errors that are machine readable using this package:

https://github.com/thebigredgeek/apollo-errors

like image 153
Andrew Rhyne Avatar answered Oct 06 '22 16:10

Andrew Rhyne


Usually it's enough. You can define error code (2 parameter), error message and any custom object in extensions (3 parameter)

     throw new ApolloError('User already exist',
                           'DUPLICATE',
                           { 'session': session })
like image 34
Аксенов Владимир Avatar answered Oct 06 '22 17:10

Аксенов Владимир