skip to Main Content

i’v been stuck for quite while now i get this error which says UnhandledPromiseRejectionWarning which is not the case i did catch error in my form controller

npm version

"@sendgrid/mail": "^6.4.0"

when i try to send email using postman Body :

(node:1504) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)

this object i get from catching the error

code: 403,
  response: {
    headers: {
      server: 'nginx',
      date: 'Fri, 16 Apr 2021 04:16:35 GMT',
      'content-type': 'application/json',
      'content-length': '281',
      connection: 'close',
      'access-control-allow-origin': 'https://sendgrid.api-docs.io',
      'access-control-allow-methods': 'POST',
      'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
      'access-control-max-age': '600',
      'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html',
      'strict-transport-security': 'max-age=600; includeSubDomains'
    },
    body: { errors: [Array] }
  }
}

 {
        "name":"fares",
        "email":"[email protected]",
        "message":"This is test This is testThis is testThis is testThis is testThis is testThis is testThis is testThis is testThis is testThis is testThis is testThis is testThis is testThis is testThis is test This is test" 
}

form controller for email

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

    exports.contactForm = (req, res) => {
        const { email, name, message } = req.body;
        // console.log(req.body);
    
        const emailData = {
            to: process.env.EMAIL_TO,
            from: email,
            subject: `Contact form - ${process.env.APP_NAME}`,
            text: `Email received from contact from n Sender name: ${name} n Sender email: ${email} n Sender message: ${message}`,
            html: `
                <h4>Email received from contact form:</h4>
                <p>Sender name: ${name}</p>
                <p>Sender email: ${email}</p>
                <p>Sender message: ${message}</p>
                <hr />
                <p>This email may contain sensetive information</p>
            `
        };
    
        sgMail.send(emailData).then(sent => {
            return res.json({
                success: true
            }).catch(error=>{
                console.log('error',error)
            })
        
        });
    };
    
    exports.contactAssignmentAuthorForm = (req, res) => {
        const { authorEmail, email, name, message } = req.body;
        // console.log(req.body);
    
        let maillist = [authorEmail, process.env.EMAIL_TO];
    
        const emailData = {
            to: maillist,
            from: email,
            subject: `Someone messaged you from ${process.env.APP_NAME}`,
            text: `Email received from contact from n Sender name: ${name} n Sender email: ${email} n Sender message: ${message}`,
            html: `
                <h4>Message received from:</h4>
                <p>name: ${name}</p>
                <p>Email: ${email}</p>
                <p>Message: ${message}</p>
                <hr />
                <p>This email may contain sensetive information</p>
         
            `
        };
    
        sgMail.send(emailData).then(sent => {
            return res.json({
                success: true
            }).catch((error) => {
                console.log('error', error);
            });
        });
    };

form routes

const express = require('express');
const router = express.Router();
const { contactForm, contactAssignmentAuthorForm } = require('../controllers/form');

// validators
const { runValidation } = require('../validators');
const { contactFormValidator } = require('../validators/form');

router.post('/contact', contactFormValidator, runValidation, contactForm);
router.post('/contact-assignment-author', contactFormValidator, runValidation, contactAssignmentAuthorForm);

module.exports = router;

form validator

const { check } = require('express-validator');

exports.contactFormValidator = [
    check('name')
        .not()
        .isEmpty()
        .withMessage('Name is required'),
    check('email')
        .isEmail()
        .withMessage('Must be valid email address'),
    check('message')
        .not()
        .isEmpty()
        .isLength({ min: 15 })
        .withMessage('Message must be at least 20 characters long')
];

env file

NODE_ENV=development
APP_NAME=SUIVISTAGE
PORT=8000
CLIENT_URL=http://localhost:3000
DATABASE_LOCAL='mongodb://localhost:27017/stage'
JWT_SECRET=KDJHF7823RHIU3289FJ932I2G8FG239
SENDGRID_API_KEY=SG.5YsBW3I7Ra2IcLLiJXfc1g.R1XYPG3SyWfyl0G1w0D5hsh5CGvECIvjYSjRcHtisDc
[email protected]

2

Answers


  1. Chosen as BEST ANSWER

    The problem has been solved by following This guide sendgrid.com/docs/ui/sending-email/sender-verification you need to verify your sender in order for this to be completed


  2. You are using catch on the wrong line, res.json doesn’t require catch block. attach catch block to sendgrid.then method like below

        sgMail.send(emailData).then(sent => {
            return res.json({
                success: true
            })
        }).catch(error=>{
           console.log('error',error)
        })
    

    Also, don’t post your API keys like this in public, they are not needed to understand your code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search