mailLib.send() in a try-catch but errors not caught

Enonic version: 6.11.0
OS: OSX

I want to send an email when a form is submitted with Ajax. If anything goes wrong with sending the email then I want to log the form responses so they’re not lost. I therefore put the mail sending code in a try-catch, but the catch never happens.

I don’t have a local SMTP server configured so I expected the mailLib to throw an error. I do see an error in the log, but it is not caught by the “catch” and so the log.warning doesn’t happen. Is this how it’s supposed to work?

var emailSent = false;
try {
    emailSent = mailLib.send({
        from: config.contactFormFromEmail,
        to: config.contactFormToEmail,
        subject: "New contact",
        body: message
    });
    if (!emailSent) {
        log.info("If you're reading this then the email did not send due to some kind of error and I would expect the catch block to run but it doesn't.");
    }
} catch (e) {
    log.warning('Contact form email did not send. \n' + message);
}

Notice I added the if(!emailSent) so now I can still get the form responses in the log when there is a problem with sending the email. So this is not high priority by any means, just not how I expected it to work.

1 Like

This is how it is supposed to work. If the mail cannot be sent the function returns false. If there is any exception during the sending it is also logged by the library.
Your code would work the same and be more simple by removing the wrapping try-catch.

The idea is that the caller is normally only interested in if the mail was sent or not. There is a long list of possible errors why it might fail.

In my opinion, making the caller check for errors with a try-catch just makes the JavaScript code more verbose. Also handling types of errors in JavaScript with a catch is not very smooth, because the exception value is not strongly typed.

1 Like

Not a bug then. It just kind of caught me by surprise but it makes sense how you explain it. Thanks Alex.

1 Like