question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Custom error message

See original GitHub issue

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!

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
jhnferrariscommented, 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. 😃

0reactions
dakshshah96commented, Mar 25, 2018

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

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to Make a Fake Error Message in Windows - wikiHow
1. Open the Notepad app. Press the ⊞ Win+R keys simultaneously. Type notepad into the Run dialog. Hit Enter or click OK. 2. Copy and paste...
Read more >
Custom Error Messages - express-validator
Custom Error Messages ... express-validator's default error message is a simple Invalid value . That's enough to cover all fields without being too...
Read more >
Providing custom error messages for built-in HTML5 form ...
How to customize built-in form validation error messages · Grab the input element(s) with a querySelector / querySelectorAll . · Add an event ......
Read more >
Flutter Custom Error Message - Flash Message - YouTube
Flutter Shop UI Kit: https://cutt.ly/rFOscFoPackage: https://pub.dev/packages/awesome_snackbar_content▻ Source Code : ...
Read more >
Return Custom Error Message for Any Issue in Power Query
Learn how to return custom error messages whenever any applied step in a Power Query query fails. More info about the m code...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found