I like a lot to make reusable .js files that I put in almost any project I participate. When i have time it will become a module.
For my errors i create a exceptions.js
file and add it on my files.
Here is the example of the code inside this file:
const util = require('util');
/**
* This exception should be used when some phat of code is not implemented.
* @param {String} message Error message that will be used inside error.
* @inheritDoc Error
*/
function NotImplementedException(message) {
this.message = message;
Error.captureStackTrace(this, NotImplementedException);
}
util.inherits(NotImplementedException, Error);
NotImplementedException.prototype.name = 'NotImplementedException';
module.exports = {
NotImplementedException,
};
In the other files of my project i must have this require line on top of the file.
const Exceptions = require('./exceptions.js');
And to use this error you just need this.
const err = Exceptions.NotImplementedException(`Request token ${requestToken}: The "${operation}" from "${partner}" does not exist.`);
Example of a full method implementation
const notImplemented = (requestToken, operation, partner) => {
logger.warn(`Request token ${requestToken}: To "${operation}" received from "${partner}"`);
return new Promise((resolve, reject) => {
const err = Exceptions.NotImplementedException(`Request token ${requestToken}: The "${operation}" from "${partner}" does not exist.`);
logger.error(err.message);
return reject(err);
});
};