graphql-constraint-directive
graphql-constraint-directive copied to clipboard
originalError not available in formatError
Hello,
I am using graphql-constraint-directive with apollo-server-express But in formatError, when I call error.originalError it always return undefined. Here my code:
const { constraintDirective, constraintDirectiveTypeDefs } = require('graphql-constraint-directive')
const express = require('express')
const { ApolloServer } = require('apollo-server-express')
const { makeExecutableSchema } = require('graphql-tools')
const typeDefs = `
type Query {
books: [Book]
}
type Book {
title: String
}
type Mutation {
createBook(input: BookInput): Book
}
input BookInput {
title: String! @constraint(minLength: 5, format: "email")
}`
const schema = makeExecutableSchema({
typeDefs: [constraintDirectiveTypeDefs, typeDefs],
schemaTransforms: [constraintDirective()]
})
const formatError = function (error) {
if (error.originalError && error.originalError.code === 'ERR_GRAPHQL_CONSTRAINT_VALIDATION') {
// return a custom object
}
console.log(error);
return error
}
const app = express()
const server = new ApolloServer({ schema, formatError })
server.applyMiddleware({ app })
app.listen({ port: 3000 }, () =>
console.log(`🚀 Server ready at http://localhost:3000${server.graphqlPath}`)
);
Please help me how can I fix it.
How are you using it? The debugger or console.log(util.inspect(error, {showHidden: true, depth: null})) should show the details. From what I recall, either GraphQL or Apollo defines them as hidden properties so a simple console.log won't show them.
Thank you for your reply. When I use console.log(util.inspect(error, {showHidden: true, depth: null})) it was show the details. But when I log the message, it still not show anything:
console.log(util.inspect(error, {showHidden: true, depth: null}))
if (error.originalError && error.originalError.code == 'ERR_GRAPHQL_CONSTRAINT_VALIDATION') {
console.log(error.originalError.message);
}
Please help me how can I show the message?
Is this solved?
Hey @confuser Is there a way to enable what fields to be included for error that is seen through util.inspect but is hidden by graphql? I am really struggling to get the format error work since error doesn't have originalError right now.
I fixed returning my errors to the frontend by adding the following code:
formatError: error => {
// @ts-ignore
if (error.originalError?.originalError?.code === 'ERR_GRAPHQL_CONSTRAINT_VALIDATION') {
// @ts-ignore
return {
// @ts-ignore
...error.originalError?.originalError,
message: error.originalError?.message,
name: 'UserInputError',
code: 'BAD_USER_INPUT',
};
}
return error;
},