node.js - catch error thrown in a mongoose callback
<p>In my controller, I have an end point function that calls another function, expecting to get a result or catch errors from the called function.</p>

<pre><code>exports.createInvites = (req, res) =&gt; { 
  // code...

  try {

    generateInvitations(requirements, data =&gt; {

      res.status(200).json({data});
    });

  } catch (err) {
    console.log(`caught the error: ${err}`);

    return res.status(500).json(err);
  }
}
</code></pre>

<p>In the called function <code>generateInvites</code>, I save generated object to mongodb using mongoose, and throw an error if there is one.</p>

<pre><code>function generateInvitations(requirements, cb) {

  const { expirationDate, credits, numOfUse, numOfInvites } = requirements;
  let invitationCodes = [];
  for (let i = 0; i &lt; numOfInvites; i++) {

    const code = randomString(CODE_LENGTH);
    invitationCodes.push(code);

    const invitation = new Invitation({
      // code,
      numOfUse,
      expirationDate,
      credits
    });

    invitation.save((err, obj) =&gt; {

      if (err) {
        throw err; // it should throw a ValidationError here
      }
    });
  }
  cb(invitationCodes);

}
</code></pre>

<p>Above code is my attempt to handle errors thrown in <code>generateInvites</code>. Of course, I wasnt able to catch any error. What did I do wrong? and what should I do instead ?</p>