function foobar() {
throw Error('Omg something happend');
}
const errors = {
NO_USER: 'There is no such user',
NO_CONNECTION: 'Database connections is closed',
};
function foobar(cb) {
cb(errors.NO_USER);
}
foobar(function(err, res) {
if (err) {
console.log(err);
return;
}
// oh yeah no errors
});
TLDR; Subclassing is not the solution
https://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript
const { createErrorClass } = require('errors-helpers');
const AppError = createErrorClass(
'AppError',
'Error in application',
Error // parent error class, optional
);
/* AppError is our custom error class */
const RuntimeError = createErrorClass(
'RuntimeError',
'Runtime error',
AppError
);
const cause = new Error();
cosnt e = new RuntimeError(extraData, cause);
e instanceof AppError === true
e instanceof Error === true
/* AppError is our custom error class */
const {
hasErrorClass
} = require('errors-helpers').helpers;
const RuntimeError = createErrorClass(
'RuntimeError',
'Runtime error',
AppError
);
const cause = new Error();
const e = new RuntimeError(extraData, cause);
// checks all causeBy recursively
hasErrorClass(e, Error) === true
/* AppError is our custom error class */
const {
getFullName
} = require('errors-helpers').helpers;
const RuntimeError = createErrorClass(
'RuntimeError',
'Runtime error',
AppError
);
const cause = new Error();
const e = new RuntimeError(extraData, cause);
// checks all causeBy recursively
getFullName(e) === 'Error.AppError.RuntimeError'
/* AppError is our custom error class */
const {
getObject
} = require('errors-helpers').helpers;
const RuntimeError = createErrorClass(
'RuntimeError',
'Runtime error',
AppError
);
const e = new RuntimeError({ lol: 'kek' });
getObject(e);
/* {
name: 'RuntimeError',
message: 'RuntimeError
data: { lol: 'kek' },
causedBy: null,
stack: '...',
} */
/* AppError is our custom error class */
const {
createErrorsList
} = require('errors-helpers').helpers;
const errors = createErrorsList({
BestError: 'This is best error message',
OmgError: 'This is OMG error',
}, AppError);
const e = new errors.BestError({ lol: 'kek' });
e instanceof AppError === true