Giter VIP home page Giter VIP logo

Comments (5)

jhnferraris avatar jhnferraris commented on May 16, 2024 1

@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. :)

from graphql-shield.

maticzav avatar maticzav commented on May 16, 2024

@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

from graphql-shield.

dakshshah96 avatar dakshshah96 commented on May 16, 2024

@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..

from graphql-shield.

jhnferraris avatar jhnferraris commented on May 16, 2024

@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.

from graphql-shield.

dakshshah96 avatar dakshshah96 commented on May 16, 2024

@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!

from graphql-shield.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.