I'm providing all the necessary details for this question, however I am confused as to why my callback function is returning an Unhandled Promise Rejection even though I deliberately want to catch the error:
(node:3144) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
(node:3144) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The function is being called in routes like this:
router.route("/home/create")
.post(Authorization, function(req, res) {
CreateSnippetResource(req, function(err) {
if (err) {
console.log(err.message)
}
res.redirect("/home")
});
});
This is the "CreateSnippetResource" function:
(function() {
let User = require("../../Models/User");
let Snippet = require("../../Models/Snippet");
/**
* Create a new snippet and save it to database
* @param request
* @param callback
*/
module.exports = function(request, callback) {
callback(
User.findOne({ user: request.session.Auth.username }, function(err, user) {
if (err || user === null) {
callback("User not found")
}
var snippet = new Snippet({
title: request.body.snippetName.split(".").shift(),
fileName: "." + request.body.snippetName.split(".").pop(),
postedBy: user._id,
snippet: [{
text: " "
}]
});
snippet.save().then().catch(function(err) {
callback(err)
});
}))
};
}());
I have implemented a validator in my schema-module to handle errors when title is not entered. The validator looks like this:
SnippetSchema.path("title").validate(function(title) {
return title.length > 0;
}, "The title is empty");
Even though the returned error message from the callback CreateSnippetResource
is The title is empty
, I am still encountering this Promise error. It seems related to how I handle the snippet.save()
, but I can't figure out where the issue lies. Can someone provide assistance?