node.jspromisesendgridquotaunhandled

How to catch Unauthorized Sendgrid Error when quota is reached?


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.


Solution

  • 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