They are correct.
The call to myCustomFunction
assumes that a promise is returned at all times (.then
and .catch
deal with resolved and rejected promises, respectively). When you throw an error, the function doesn't return a promise.
You could use this to catch the error:
try {
myModule.myCustomFunction(someInput).then(result => {
// carry on
})
.catch(err => {
// do something with the error
})
} catch(err) {
...
}
But as you can see, this results in two error handlers: try/catch
for the synchronously thrown error, and .catch
for any rejected promises that sns.createTopic(someParams)
may return.
That's why it's better to use Promise.reject()
:
module.exports.myCustomFunction = input => {
if (badInput) {
return Promise.reject('failed');
}
return sns.createTopic(someParams).promise()
}
Then, the .catch
will catch both types of errors/rejections.
NB: for newer versions of Node.js (v7.6 and up, I believe), the following will also work:
module.exports.myCustomFunction = async input => {
if (badInput) {
throw new Error('failed');
}
return sns.createTopic(someParams).promise()
}
The key here is the async keyword. By using this keyword, the function results are wrapped by a promise automatically (similar to what @peteb's answer is showing).