UNPKG

@inv2/common

Version:

A common module for v2

70 lines (69 loc) 3.01 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.handleError = exports.Exception = exports.CustomError = void 0; const sequelize_1 = require("sequelize"); ; class CustomError extends Error { constructor(params) { var _a; super(params.message); this.params = params; this.line = 0; this.file = ''; // Add this because we are extending a built in class Object.setPrototypeOf(this, CustomError.prototype); const reg = new RegExp(/at\s+((\S+)\s)?\((\S+):(\d+):(\d+)\)/); const stact = (_a = this.stack) === null || _a === void 0 ? void 0 : _a.split('\n').at(1); const caller = reg.exec(stact); (caller === null || caller === void 0 ? void 0 : caller[4]) ? this.line = parseInt(caller === null || caller === void 0 ? void 0 : caller[4]) : 0; (caller === null || caller === void 0 ? void 0 : caller[2]) ? this.file = caller === null || caller === void 0 ? void 0 : caller[2] : 0; this.params = Object.assign(Object.assign({}, this.params), { line: parseInt((caller === null || caller === void 0 ? void 0 : caller[4]) || ''), file: caller === null || caller === void 0 ? void 0 : caller[2] }); } serializeErrors() { const found = findVal(this.params, 'params'); this.params = found !== null && found !== void 0 ? found : this.params; return Object.assign({}, this.params); } } exports.CustomError = CustomError; const findVal = (object, key) => { var value; Object.keys(object).some(function (k) { if (k === key && !object[k][k]) { value = object[k]; return true; } if (object[k] && typeof object[k] === 'object') { value = findVal(object[k], key); return value !== undefined; } }); return value; }; class Exception extends CustomError { constructor(params) { super(params); this.params = params; this.params = Object.assign(Object.assign({ line: this.line, file: this.file }, this.params), params); this.code = params.code || 400; // Add this because we are extending a built in class Object.setPrototypeOf(this, Exception.prototype); } } exports.Exception = Exception; const handleError = (error) => { if (error instanceof CustomError) { throw new Exception(error); } else if (error instanceof sequelize_1.ValidationError) { return { code: 400, message: error.errors.map((e) => e.message).join(", "), success: false }; } else if (error instanceof sequelize_1.DatabaseError) { return { code: 500, message: "Database error occurred", success: false }; } else if (error instanceof sequelize_1.SequelizeScopeError) { return { code: 500, message: "Scope error with the database query", success: false }; } return { code: 500, message: "An unknown error occurred", success: false }; }; exports.handleError = handleError;