Home > Enterprise >  Node js unable to catch errors when sending an email using AWS SES
Node js unable to catch errors when sending an email using AWS SES

Time:03-17

I need to be able to catch the error that occurs during the process of sending an email using Express and AWS SES. If there occurs an error, wrong email for example, the API itself shows a CORS error while in nodemon console the error is logged there.

const AWS = require('aws-sdk');

const SES_CONFIG = {
    accessKeyId: '...',
    secretAccessKey: '...',
    region: '...',
};

const AWS_SES = new AWS.SES(SES_CONFIG);

let sendEmail = (recipientEmail, name) => {
    let params = {
        Source: '[email protected]',
        Destination: {
            ToAddresses: [
                recipientEmail
            ],
        },
        ReplyToAddresses: [],
        Message: {
            Body: {
                Html: {
                    Charset: 'UTF-8',
                    Data: 'This is the body of my email!',
                },
            },
            Subject: {
                Charset: 'UTF-8',
                Data: `Hello, ${name}!`,
            }
        },
    };
    return AWS_SES.sendEmail(params).promise();
};

The API endpoint:

router.post('/emailTest', async (req, res) => {
    try {
        sendEmail('[email protected]', '...', function (err, data) {
            if (err)
                res.send(err);
            res.send(data);
        });

    } catch (error) {
        res.json({
            Status: 500,
            header: 'Error',
            message: 'Internal Server Error. '   error.message
        });
    } })

CodePudding user response:

You are calling your sendEmail function with a callback, but your function doesn't use any callbacks. It returns a promise.

Try using await.

router.post('/emailTest', async (req, res) => {
    try {
        const data = await sendEmail('[email protected]', '...');
        res.send(data);
    } catch (error) {
        res.json({
            Status: 500,
            header: 'Error',
            message: 'Internal Server Error. '   error.message
        });
    } })
  • Related