Search code examples
javascriptthrow

Catch the error with the callback function


I wrote my middleware in order to use an external code for the management of the users account. When I'm creatin a new account I use the related function of the Manager as per following code:

.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',
                });
            }
        });
    });

But I'm not able to catch the error when, for example, the user is already existing. My UsersManager.createUser code is the following:

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 is:

Error: Uncaught, unspecified "error" event. (null)

How I should handle the last row else throw err in order to be catched by the callback? What is your opinion about my structure of the code in order to handle the user management?


Solution

  • I solved by using the following 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{
                    var err = 1;
                    callback(err);
                }
            });
    
        }