My middleware was developed to utilize an external code for managing user accounts. When creating a new account, I rely on the Manager's function with the following code snippet:
.post(function(req,res,next){
UsersManager.createUser(req.body.username,req.body.password,function(err){
if(err){
res.json({
success: false,
message: 'User NOT created',
});
}else{
res.json({
success: true,
message: 'User '+req.body.username+' created',
});
}
});
});
However, I am facing difficulty in capturing errors, such as when the user already exists. Here is the UsersManager.createUser
code:
createUser: function(username,password,callback){
var new_user = new User({
username: username,
password: password
});
User.findOne({username:username},function(err,user){
if(!user) new_user.save(callback);
else throw err;
});
}
The error message reads:
Error: Uncaught, unspecified "error" event. (null)
How can I properly handle the final line else throw err
so that it can be caught by the callback? What are your thoughts on the code structure for handling user management?