2

I have no trouble sending email with Sendgrid using this simple code:

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const sendWelcomeEmail = (email, username, code) => {
    sgMail.send({
        to: email,
        from: 'example@gmail.com',
        subject: 'Welcome!',
        html: '<h3Welcome</h3>'
    });
};

Yet when Sendgrid quota is reached (i.e 100 free email/day) I get this error on the server:

(node:5060) UnhandledPromiseRejectionWarning: Error: Unauthorized
    at Request._callback (C:\...\node_modules\@sendgrid\client\src\classes\client.js:124:25)

[...]

(node:5060) [DEP0018] 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.


I have been been trying some try catch blocks in different places without success. Thanks.

tuancharlie
  • 161
  • 6

2 Answers2

0

This is tiguchi comment, I post it as the accepted answer :

It's a NodeJS warning telling you to add error handling to that promise. Just append a .catch(error => console.error(error)) after the send call – tiguchi

tuancharlie
  • 161
  • 6
0

You can use async/await syntax and try/catch block to wrap the code, for example:

const sendWelcomeEmail = async (email, username, code) => {
  try {
    await sgMail.send({
      to: email,
      from: 'example@gmail.com',
      subject: 'Welcome!',
      html: '<h3Welcome</h3>'
  });
  } catch (err) {
    console.log(err)

    if (err.response) {
      console.error(err.response.body)
    }
  }
};
Hong Phuc
  • 63
  • 1
  • 5