To make a website interactive and user-friendly, JavaScript is the programming language that does the work. It is a widely used language for developing infinite numbers of projects. Programmers and developers all over the world use it to design projects. When you are working with JavaScript, you may encounter various errors and beginners usually make more errors as they are in a learning phase. You may experience the exception “error: cannot return null for non-nullable field”.
As the error itself says, it can’t return a null when the field is set to non-nullable. Errors always seem quite frustrating, and the same goes for this one, right? Well, don’t worry as we have a solution to fix the error. First, have a look at how you get the error warning
How the error pops up
When trying to use a program on the server side, you get the following error
Cannot return null for non-nullable field
The program code that results in the error is:
Schema
export default `
type User {
id: ID!
name: String!
email: String!
}
type Query {
allUsers: [User]
currentUser: User
}
type Mutation {
createAccount(name: String!, email: String!, password: String!): User
loginUser(email: String!, password: String!): User
updatePassword(email: String!, password: String!, newPassword: String!): User
deleteAccount(email: String!, password: String!): User
}
`
The Resolvers
createAccount: async (
parent,
{ name, email, password },
{ User },
info
) => {
try {
// Check for invalid (undefined) credentials
if (!name || !email || !password) {
return 'Please provide valid credentials';
}
// Check if there is a user with the same email
const foundUser = await User.findOne({ email });
if (foundUser) {
return 'Email is already in use';
}
// If no user with email create a new user
const hashedPassword = await bcrypt.hash(password, 10);
await User.insert({ name, email, password: hashedPassword });
const savedUser = await User.findOne({ email });
return savedUser;
} catch (error) {
return error.message;
}
},
That’s exactly the program code that gets you in the error warning
How To Fix the Error “error: cannot return null for non-nullable field”
The cause of the error is the resolver that you used in the code. A string is returned rather than a user. According to the scenario, a null or a user can be returned by createAccount added in the schema. But, in case it’s a user, then it must be non-nullable, and thus, null is not a valid type. Have a look at the solution to resolve it
Solution
The resolver you have used in the code can show any exceptions needed as it will be returned in the errors arrays. Check out the instance
// Check if there is a user with the same email
const foundUser = await User.findOne({ email })
if (foundUser) throw new Error('Email is already in use')
// If no user with email create a new user
const hashedPassword = await bcrypt.hash(password, 10);
await User.insert({ name, email, password: hashedPassword });
const savedUser = await User.findOne({ email });
return savedUser;
In the case of duplicate email, you get the following response
{
"data": {
"createAccount": null
},
"errors": [
{
"message": "Email is already in use",
"locations": [
{
"line": 4,
"column": 3
}
],
"path": [
"createAccount"
]
}
]
}
If you want to check how errors are visible on the client, you have the option to either use formatResponse or formatError to configure for the middleware Apollo server. Using custom errors is a good approach that permits to include custom properties to simply determine the type of error on the client end.
Conclusion
The solution highlighted in the post is the best way to handle the error warning “error: cannot return null for non-nullable field”. It is easy to implement and helps you remove the error.
I hope you find it useful!