Módulo para uso de exportación
/**
* Custom InputError
*/
class InputError extends Error {
/**
* Create InputError
* @param {String} message
*/
constructor(message) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
/**
* Custom AuthError
*/
class AuthError extends Error {
/**
* Create AuthError
* @param {String} message
*/
constructor(message) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
/**
* Custom NotFoundError
*/
class NotFoundError extends Error {
/**
* Create NotFoundError
* @param {String} message
*/
constructor(message) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = {
InputError: InputError,
AuthError: AuthError,
NotFoundError: NotFoundError
};
Importar al script:
const {InputError, AuthError, NotFoundError} = require(path.join(process.cwd(), 'lib', 'errors'));
Utilizar:
function doTheCheck = () =>
checkInputData().then(() => {
return Promise.resolve();
}).catch(err => {
return Promise.reject(new InputError(err));
});
};
Código de llamada externo:
doTheCheck.then(() => {
res.send('Ok');
}).catch(err => {
if (err instanceof NotFoundError) {
res.status(404).send('Not found');
} else if (err instanceof AuthError) {
res.status(301).send('Not allowed');
} else if (err instanceof InputError) {
res.status(400).send('Input invalid');
} else {
console.error(err.toString());
res.status(500).send('Server error');
}
});
Error
tiene problemas. Ver stackoverflow.com/questions/1382107/…