'Node js unable to catch errors when sending an email using AWS SES

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
        });
    } })


Solution 1:[1]

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
        });
    } })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jkoch