Experience the convenience of Apollo GraphQL with its user-friendly type-validation error messages

I am currently in the process of developing an app that utilizes Apollo for my GraphQL API. GraphQL offers type and non-nullable checking for certain fields. For instance, if I want the foo field to be of type Int and a non-nullable field, I can specify this in the schema (or typedefs).

foo: Int!

This setup may result in an error like:

"message": "Variable \"$input\" received invalid value \"foo\"; Expected type Int; Int cannot represent non 32-bit signed integer value: foo"\

However, imagine I wish to customize the error message to something like:

"message": "Foo is wrong"

Is it feasible to modify the default error message? While handling non-nullables in resolvers is technically achievable, altering error messages for types seems challenging.

Answer №1

To modify the error messages generated during the serialization or parsing of scalars, one approach is to create custom implementations for those scalars. For instance, you can reference the source code for your desired scalar:

const { GraphQLScalarType } = require('graphql')
const inspect = require('graphql/jsutils/inspect').default

function serializeCustomScalar(rawValue) {
  const value = serializeObject(rawValue);

  if (typeof value === 'string') {
    return value;
  }
  if (Number.isInteger(value)) {
    return String(value);
  }
  throw new TypeError(`CustomScalar cannot represent value: ${inspect(rawValue)}`);
}

function coerceCustomScalar(value) {
  if (typeof value === 'string') {
    return value;
  }
  if (Number.isInteger(value)) {
    return value.toString();
  }
  throw new TypeError(`Oops! CustomScalar cannot represent value: ${inspect(value)}`);
}

const CustomScalar = new GraphQLScalarType({
  name: 'CustomScalar',
  description:
    'The `CustomScalar` type represents a unique identifier, often used for various purposes. It appears as a String in JSON responses but is not intended for human readability.',
  serialize: serializeCustomScalar,
  parseValue: coerceCustomScalar,
  parseLiteral(ast) {
    return ast.kind === Kind.STRING || ast.kind === Kind.INT
      ? ast.value
      : undefined;
  },
})

const resolvers = {
  CustomScalar,
  /* additional resolvers */
}

The updated validation message will now appear as follows:

Variable \"$id\" received an invalid value true; Expected type CustomScalar; Oops! CustomScalar cannot represent value: true

Note that altering the initial part of the message is not feasible.

In the event of validation errors, it indicates issues within your code - either on the client side (for input validation) or server-side (for output validation). Users should ideally not be exposed to such errors and instead receive a more generic error message.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trigger an event in Angular using TypeScript when a key is pressed

Is it possible to activate a function when the user presses the / key in Angular directly from the keydown event? <div (keydown.\)="alerting()"> </div> <div (keydown.+)="alerting()"> </div> Both of these ...

Unable to build an optional Node.js dependency using the Angular compiler

Within my npm library, there exists a code snippet that appears as follows: let _Buffer: typeof Buffer; let _require: NodeRequire; let _readFile: (path: string, callback: (err: (NodeJS.ErrnoException | null), data: Buffer) => void) => void; try { ...

Prevent dropzone from refreshing the page

For the past few days, I have been scouring the internet for solutions on how to prevent a page from automatically reloading after an upload. Despite finding various methods, I have been unsuccessful in resolving this issue. Although I am following the st ...

Receiving the final outcome of a promise as a returned value

Seeking to deepen my comprehension of promises. In this code snippet, I am working on creating two promises that will return the numbers 19 and 23 respectively. However, when attempting to console log the value returned from the first promise, I encounte ...

Mastering the ng-if directive in Angular can help you easily display or hide content based on boolean

Having trouble figuring out what to insert in the last span element where it mentions "I_DO_NOT_KNOW", here is the markup provided: <div class="row"> <div class="key" translate>Label</div> <div class="value form-group"> < ...

Implementing a callback in the app.get function within Node.js: A step-by-step guide

I have a fully functioning website and now I am looking to add some logic and data analysis to it. Below is the code snippet for rendering my /data page: app.get("/data", (req, res) => { const sql = "SELECT * FROM MyMoods"; cons ...

methods for verifying changing row array data in javascript

Can someone please provide guidance on how to validate the array values in JavaScript? Below is the code I am currently using. The issue I am facing is that even after filling up all the values, I still receive a validation error message. Please advise me ...

Retrieve a specific item from a JSON response using Node.js

When I receive a message from a WebSocket, the code snippet is triggered like this: ws.onmessage = (e) => { debugger if (e.data.startsWith('MESSAGE')) alert(JSON.stringify(e.data)) ImageReceived(e.data) c ...

Is it possible to modify the color of a span element within a select dropdown?

Is there a way to change the color of a span to red within a select option in js fiddle? I am trying to modify the color of <span class="myError">This is a required field.</span> to red https://i.sstatic.net/nRF2c.png select{ color: green; ...

Sequentially iterate through elements based on their Data attributes

Assume you are working with HTML elements like the ones shown below <span class="active" data-id="3"> Test 3 </span> <span class="active" data-id="1"> Test 1 </span> <span class="activ ...

Storing the many-to-many field when creating an object in Django DRF

Excuse me if this may seem like a straightforward question. I have looked for various solutions, but none of them seem to address my specific issue. I am dealing with a model that has a many-to-many field relationship. Whenever I create a new object throu ...

Having trouble parsing a Laravel JSON object in Javascript and encountering errors

This is a snippet of Laravel code: $teachers = Teachers::where('possessed_by_community', $communityId)->pluck('teacher_name'); return view('pages.show_add_teachers', [ 'teachers' => $teachers ]); When I ...

Guide to iterating within a loop with a variable number of iterations above or below the specified amount in JavaScript

I am currently engaged in a project for a small theater group, and I am facing challenges with getting this loop to execute properly. <% include ../partials/header %> <div class="jumbotron jumbotron-fluid"> <div class="container"> ...

The custom AJAX user control's JavaScript constructor is encountering an "element" that is undefined

I am attempting to develop a customized AJAX user control that includes a client-side object as well. Despite following the guidelines provided in this resource: https://msdn.microsoft.com/en-us/library/bb398906.aspx, I am encountering persistent issues. ...

Filtering and pagination on the server side using AngularJS

Currently, I am dealing with several input fields. Let's take the example of an input field named "search". My goal is to filter the results of an object when someone types into that field; however, I prefer to perform this filtration on the server si ...

Data of an object disappears when it is passed to Meteor.call

In my React/Meteor project, I encountered an issue while trying to pass an object with data from the state to a method on the server for database insertion. Surprisingly, when the object is passed from the React component to the Meteor method, one of the c ...

The operation of "grunt build" results in a Lexer Error, causing the ng-include

After deploying my unminified code successfully, I proceed to run grunt build and deploy from the dist folder. However, upon checking one of the pages, I encounter a breakage with an error in the console: Error: [$parse:lexerr] Lexer Error: Unexpected nex ...

Having numerous sections condensed into one cohesive page

Currently, I am working with backbone.js to develop a single-page application that takes inspiration from the functionality of trello.com. I am interested in learning how to display multiple pages on top of the original page and effectively structure the ...

Issue with form validation causing state value to remain stagnant

Giving my code a closer look, here is a snippet in HTML: <input type="text" name="email" id="email" autoComplete="email" onChange={(e) => {validateField(e.target)}} className="mt-1 ...

Determine if checkboxes exist on a webpage using jQuery

I am facing a situation where a form is dynamically loaded via ajax. Depending on the parameters passed to retrieve the form, it may or may not contain checkboxes. I am looking for a way to verify the presence of checkboxes on the page and prompt the user ...