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.