nestjs-mapped-exception
Version:
Mapped Exceptions for NestJS
61 lines • 2.48 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MappedException = void 0;
const mapped_exception_error_class_1 = require("./mapped-exception-error.class");
const mapped_exceptions_item_class_1 = require("./types/mapped-exceptions-item.class");
class MappedException {
constructor(exception, options) {
this.options = Object.assign({}, options);
let instance = new exception();
if (!this.options.suffix) {
this.options.suffix = this.suffixFromExceptionInstance(instance);
}
instance = this.setupExceptions(instance);
this.ERRORS = instance;
}
setupExceptions(exceptionClass) {
Object.getOwnPropertyNames(exceptionClass).map((item, index) => {
const mappedExceptionItem = this.isValidMappedExceptionItemOrFail(exceptionClass[item]);
mappedExceptionItem.code = this.getExceptionItemCode(mappedExceptionItem, index);
if (!mappedExceptionItem.throw) {
mappedExceptionItem.throw = this.getThrowFunction(mappedExceptionItem);
}
exceptionClass[item] = mappedExceptionItem;
});
return exceptionClass;
}
isValidMappedExceptionItemOrFail(item) {
if (item.message && item.statusCode) {
return new mapped_exceptions_item_class_1.MappedExceptionItem(item);
}
throw new Error('Invalid Exception item');
}
getThrowFunction(exceptionItem) {
return () => {
throw new mapped_exception_error_class_1.MappedExceptionError(exceptionItem);
};
}
getExceptionItemCode(exceptionItem, index) {
if (exceptionItem.code) {
if (typeof exceptionItem.code === 'string') {
if (isNaN(Number(exceptionItem.code))) {
return exceptionItem.code;
}
}
return this.generateExceptionItemCode(+exceptionItem.code);
}
return this.generateExceptionItemCode(index);
}
generateExceptionItemCode(code) {
return `${this.options.prefix}${code.toString().padStart(4, '0')}${this.options.suffix}`;
}
suffixFromExceptionInstance(exceptionClass) {
return exceptionClass.constructor.name
.toString()
.substring(0, 3)
.toUpperCase()
.padStart(3, '_');
}
}
exports.MappedException = MappedException;
//# sourceMappingURL=mapped-exception.class.js.map