In Node.js I have a module which consists of just one function. The function returns promise and the promise could be rejected. Still I don\'t want to force all users of the
If you're concerned about unhandled rejections causing your Nodejs process to terminate unintentionally in the future, you could register an event handler for the 'unhandledRejection' event on the process object.
process.on('unhandledRejection', (err, p) => {
console.log('An unhandledRejection occurred');
console.log(`Rejected Promise: ${p}`);
console.log(`Rejection: ${err}`);
});
If you want the implementing user of your module to decide whether or not to handle the error in their code, you should just return your promise to the caller.
yourModule.js
function increment(value) {
return new Promise((resolve, reject) => {
if (!value)
return reject(new Error('a value to increment is required'));
return resolve(value++);
});
}
theirModule.js
const increment = require('./yourModule.js');
increment()
.then((incremented) => {
console.log(`Value incremented to ${incremented}`);
})
.catch((err) => {
// Handle rejections returned from increment()
console.log(err);
});