UNPKG

@kcutils/error

Version:
298 lines (289 loc) 11.3 kB
import'path';import {Writable}from'stream';var notExist = function (t) { return t === undefined || t === null; };/** * checking is input is object datatype (object mean typeof input will return object) * * @param obj input of any type */ var isObject = function (obj) { if (obj === undefined || obj === null) return false; else return typeof obj === "object" && !Array.isArray(obj); };/** * return true when match following condition * 1. is undefined or null * 2. is empty string * 3. is empty object ({}) * 4. is empty array ([]) * * @param t input on any data type */ /* global Reflect, Promise */ var extendStatics$1 = function(d, b) { extendStatics$1 = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics$1(d, b); }; function __extends$1(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics$1(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }var setImmediate = function (fn) { setTimeout(fn, 0); }; /** * This can use in all Writeable object to write data to /dev/null channel */ /** @class */ ((function (_super) { __extends$1(DevNull, _super); function DevNull() { return _super.call(this) || this; } Object.defineProperty(DevNull, "instance", { get: function () { return new DevNull(); }, enumerable: false, configurable: true }); DevNull.prototype._write = function (_chunk, _encoding, callback) { return setImmediate(callback); }; return DevNull; })(Writable));/** * convert input to array size 1 if not, * or return input if already be array type * * @param t input value * @returns array */ var isExist = function (t) { return t !== undefined && t !== null; };var isBoolean = function (t) { return isExist(t) && typeof t === "boolean"; };var isNumber = function (t, ignoreSpecial) { if (ignoreSpecial === void 0) { ignoreSpecial = false; } if (isExist(t)) { if (typeof t === "number") { if (ignoreSpecial) return true; else return !isNaN(t) && isFinite(t); } } return false; };var isString = function (t) { return isExist(t) && typeof t === "string"; };var cleanObject = function (obj) { if (notExist(obj)) return {}; else return Object.keys(obj).reduce(function (p, k) { var _a; var v = obj[k]; if (isExist(v)) return __assign(__assign({}, p), (_a = {}, _a[k] = v, _a)); else return p; }, {}); };var mergeObject = function (base) { var obj = []; for (var _i = 1; _i < arguments.length; _i++) { obj[_i - 1] = arguments[_i]; } var newObjectList = obj.map(function (o) { return cleanObject(o); }); return Object.assign.apply(Object, __spreadArray([cleanObject(base)], newObjectList, false)); };var serializer = function (replacer, cycleReplacer) { var stack = []; var keys = []; if (notExist(cycleReplacer)) { cycleReplacer = function (_key, value) { if (stack[0] === value) return "[Circular]"; return "[Circular." + keys.slice(0, stack.indexOf(value)).join(".") + "]"; }; } return function (key, value) { if (stack.length > 0) { var thisPos = stack.indexOf(this); ~thisPos ? stack.splice(thisPos + 1) : stack.push(this); ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key); if (~stack.indexOf(value) && isExist(cycleReplacer)) { value = cycleReplacer.call(this, key, value); } } else stack.push(value); return notExist(replacer) ? value : replacer.call(this, key, value); }; }; /** * same with {@link JSON.stringify()} * this function copy from {@link https://github.com/moll/json-stringify-safe} * * @param obj similar object you would pass to JSON.stringify * @param replacer same with replacer in JSON.stringify * @param spaces same with spaces in JSON.stringify * @param cycleReplacer same with replacer in JSON.stringify but for cycle object * @returns text represent input object */ var stringify = function (obj, replacer, spaces, cycleReplacer) { return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces); };var hasToString = function (input) { if (input === undefined || input === null) return false; return !!input.toString; }; /** * Cast input to string. This supporting by listed below * * 1. undefined | null => return undefined * 2. boolean | string => return as string * 3. number => return as fix digit not more than 6 * 4. array => return as array syntax without space * 5. object => return by object.stringify() * * @param input input data on any type */ var toString = function (input) { if (Array.isArray(input)) return "[".concat(input.join(","), "]"); else if (isNumber(input)) return input.toString(10); else if (isString(input)) return input; else if (isBoolean(input)) return input ? "true" : "false"; // Must be JSON object, not custom object else if (isObject(input) && input.constructor === Object) return stringify(input); // Custom object should falling here else if (hasToString(input)) return input.toString(); else return undefined; };/** * Add <fill> on the end if not enough or remove character if exceed * * @param str input string * @param length string limitation * @param fill character for fill if input is not long enough * @returns string with exactly length size */ var replace = function (format, argument) { return format.replace(/{(\w+)}/g, function (match, key) { var _a; return (_a = toString(argument[key])) !== null && _a !== void 0 ? _a : match; }); };/*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }var Err = /** @class */ (function (_super) { __extends(Err, _super); function Err(name, template, data, stack) { var _this = _super.call(this, replace(template, data !== null && data !== void 0 ? data : {})) || this; _this.name = name; _this.stack = stack; return _this; } return Err; }(Error));var Exception = /** @class */ (function (_super) { __extends(Exception, _super); function Exception(state, template, data, buildStack) { var _a; var stack; if (buildStack) { var _stack = []; var obj = { stack: [] }; var orig = Error.prepareStackTrace; // save original prepare method Error.prepareStackTrace = function (_, stack) { return stack; }; Error.captureStackTrace(obj, Exception); for (var _i = 0, _b = obj.stack; _i < _b.length; _i++) { var stack_1 = _b[_i]; _stack.push({ path: (_a = stack_1.getFileName()) !== null && _a !== void 0 ? _a : "", typename: stack_1.getTypeName(), colmnum: stack_1.getColumnNumber(), funcname: stack_1.getFunctionName(), linenum: stack_1.getLineNumber(), method: stack_1.getMethodName(), }); } Error.prepareStackTrace = orig; // revert original method stack = buildStack(_stack); } return _super.call(this, state.name, template, mergeObject(state, { stack: stack }, data)) || this; } return Exception; }(Err));var ExceptionBuilder = /** @class */ (function () { function ExceptionBuilder(option) { this._input = { code: option.code, name: option.name, type: option.type, }; this._template = option.template; this._buildStack = option.buildStack; } ExceptionBuilder.fn = function (option) { return new ExceptionBuilder(option); }; ExceptionBuilder.prototype.throw = function (data) { return new Exception(this._input, this._template, data, this._buildStack); }; ExceptionBuilder.prototype.custom = function (state, data) { return new Exception(mergeObject(this._input, state), this._template, data, this._buildStack); }; return ExceptionBuilder; }());var StateTypes; (function (StateTypes) { StateTypes["WARN"] = "WARN"; StateTypes["ERROR"] = "ERROR"; StateTypes["FATAL"] = "FATAL"; })(StateTypes || (StateTypes = {})); var StateTypes$1 = StateTypes;export{Err,Exception,ExceptionBuilder,StateTypes$1 as StateTypes};//# sourceMappingURL=index.esm.js.map