在标量的序列化或解析过程中稍微改变抛出的错误消息的唯一方法是提供这些标量的自定义实现。例如,您可以为您选择的标量复制源代码:
const { GraphQLScalarType } = require('graphql')
const inspect = require('graphql/jsutils/inspect').default
function serializeID(rawValue) {
const value = serializeObject(rawValue);
if (typeof value === 'string') {
return value;
}
if (Number.isInteger(value)) {
return String(value);
}
throw new TypeError(`ID cannot represent value: ${inspect(rawValue)}`);
}
function coerceID(value) {
if (typeof value === 'string') {
return value;
}
if (Number.isInteger(value)) {
return value.toString();
}
throw new TypeError(`Oh no! ID cannot represent value: ${inspect(value)}`);
}
const ID = new GraphQLScalarType({
name: 'ID',
description:
'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.',
serialize: serializeID,
parseValue: coerceID,
parseLiteral(ast) {
return ast.kind === Kind.STRING || ast.kind === Kind.INT
? ast.value
: undefined;
},
})
const resolvers = {
ID,
/* the rest of your resolvers */
}
现在验证消息将改为:
变量 \"$id\" 得到无效值 true;预期的类型 ID;不好了!ID不能代表值:true
但是,无法更改消息的第一部分。
也就是说,验证错误意味着您的代码出现问题,无论是在客户端(验证输入时)还是在服务器端(验证输出时)。用户可能不应该接触到这些错误,而应该显示一些通用的错误消息。