error3
Version:
Error3 is proper JS error implementation. It supports error codes, message formatting (e.g. i18n) and nested errors.
95 lines (91 loc) • 3.54 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.Error3 = factory());
}(this, function () { 'use strict';
var __extends = (undefined && undefined.__extends) || (function () {
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 (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (undefined && undefined.__assign) || function () {
__assign = Object.assign || function(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);
};
var Error3 = /** @class */ (function (_super) {
__extends(Error3, _super);
function Error3(details, errors) {
var _this = _super.call(this) || this;
_this.code = 0;
_this.name = _this.constructor.name;
if (details) {
if (isObject(details) && isPlainObject(details)) {
_this.details = __assign({}, details);
}
else {
throw new Error('Details should be a plain Object instance or undefined');
}
}
else {
_this.details = {};
}
if (errors) {
if (isErrors(errors)) {
_this.errors = errors;
}
else {
throw new Error('Errors should be an array of errors');
}
}
else {
_this.errors = [];
}
_this.message = _this.format(details, errors);
return _this;
}
Error3.prototype.valueOf = function () {
return {
code: this.code,
message: this.message,
details: this.details,
errors: this.errors.map(function (error) { return error.valueOf(); }),
};
};
Error3.prototype.toString = function () {
var _a = this, name = _a.name, code = _a.code, message = _a.message;
return name + ": [#" + code + "] " + message;
};
Error3.prototype.toJSON = function () {
return this.valueOf();
};
return Error3;
}(Error));
function isErrors(value) {
return (Array.isArray(value) && value.every(function (item) { return isErrorObject(item); }));
}
function isObject(value) {
return value !== null && typeof value === 'object';
}
function isErrorObject(value) {
return isObject(value) && value instanceof Error;
}
function isPlainObject(value) {
return value.constructor.toString() === Object.toString();
}
return Error3;
}));