How to handle and return errors in an API using NodeJS / Express
<p>Im creating an a API using NodeJS with the express framework and mongodb to store my data.</p>

<p>I have a register function which does 3 main things.</p>

<ol>
<li>Creates the new.</li>
<li>Creates a token and associates it with a user.</li>
<li><p>Sends an email.</p>

<p>module.exports.register = function(req, res) {</p>

<pre><code>var input = req.body;
var token = uuid.v4();


// Create a new user
var user = new User ({

    username: input.username,
    email: input.email,
    password: input.password,
    active: false

});

user.save(function(err) {

    if(err) return res.json({success: false, errors: 'Failed To Create User'});

});


// Create a new Token
var newToken = createToken('new', null, user._id);


// Assign New Token To New User
if(newToken) {


    user.tokens.push(newToken._id);


    user.save(function(err) {

        if(err) return res.json({success: false, errors: 'Failed To Save User Token'});

    });

}


// Send Email To User
var mailData = {

    from: 'deleted@hotmail.com',
    to: input.email,
    subject: 'Activate Your Account',
    text: 'http://localhost:8080/api/auth/activate/' + token

}

mail.messages().send(mailData, function(err, body) {

    if(err) return res.json({ success: false, errors: 'Failed To Send Email' });

});


return res.json({ 
    success: true, 
    status: 'Successfully Registered User, Check Email To Activate' 
});
</code></pre>

<p>}</p></li>
</ol>

<p>Now even if there are errors whilst creating the user or the token or sending an email. It's always going to return that it successfully registered a user. How can i restructure / handle this better?</p>

<p>I also have the problem where if the email fails to send the user and token will have already been created, how do i solve this issue? Would i just create a resend activation function?</p>