Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom error message #17

Closed
jhnferraris opened this issue Feb 20, 2018 · 5 comments
Closed

Custom error message #17

jhnferraris opened this issue Feb 20, 2018 · 5 comments

Comments

@jhnferraris
Copy link

Is it possible to modify the error object?

{
  "data": null,
  "errors": [
    {
      "message": "Insufficient Permissions.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "getSurveys"
      ]
    }
  ]
}

Or can we directly use other error handler like apollo-errors instead of using the default "Insufficient permission"

Thanks for the assist!

@maticzav
Copy link
Owner

@jhnferraris custom errors are currently not supported, but I would love to hear more from you on this topic. Could you add this to roadmap thread? 🙂

#6

@dakshshah96
Copy link

@maticzav Any updates on this? I really want my developers to know what the cause of the error is. For example, JWT token has expired or something like Authorization header is required instead of just Insufficient Permissions..

@jhnferraris
Copy link
Author

@dakshshah96

Since it is still in their roadmap, we opted on using a different approach. We used graphql-resolvers's, combineResolvers. In which we have one resolver doing the "validation" and throw custom error when the validation fails.

@dakshshah96
Copy link

@jhnferraris If it's not too much trouble, can you give me an example of how custom errors can be implemented? I've already defined all of my schema using graphql-tools in my apollo-server powered GraphQL backend. Thanks!

@jhnferraris
Copy link
Author

jhnferraris commented Mar 25, 2018

@dakshshah96 Sure!

Example you have a "validation" resolver:

Resolver A: validateAuthObject

const { AuthorizationError } = require("../../errors"); // -- This is an instance of `apollo-errors`
module.exports = async (root, args, context, info) => {
  const user = _.get(args, "user", null);
  if (!user) {
    throw new AuthorizationError({
      message: "Missing user object.",
      data: {
        code: "auth-1"
      }
    });
  }
};

In your main resolver of a certain GraphQL query, let say getData(user: User, options: JSON!). We combine our validateUserObject and the "main" resolver.

const { combineResolvers } = require("graphql-resolvers");

getData: combineResolvers(validateUserObject, async (obj, args, context, info) => {
      const options = _.get(args, "options", {});
      return DataRepository.getAll(options);
    }),

Once user is null it will return t

{
  "data": null,
  "errors": [
    {
      "message": "Missing user object.",
      "name": "AuthorizationError",
      "time_thrown": "2018-03-22T10:48:42.113Z",
      "data": {
        "code": "auth-1"
      }
    }
  ]

}

Another approach is without the need for an extra resolver (if there's no need for reusability). Let's use your code here as an example:

const { UnknownError } = require('../../../helpers/errors')

const createAdmin = async (payload) => {
  try {
    const { error, value } = Joi.validate(payload, adminReqSchema)
    if (error) {
      throw new UnknownError({
        data: {
          reason: 'Schema validation error'
        }
      })
    }

    const admin = await new Admin({ name: value.name, phoneNumber: value.phoneNumber }).save()
    await new Auth({ userId: admin._id, role: 'admin', password: value.password }).save()

    return admin
  } catch (err) {
    
    console.log(err)
    throw err; // -- Re-throwing the error will allow GraphQL to immediately format the error as an `UnknownError` and will populate the `errors` field.
  }
}

I hope this helps. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants