1
0
mirror of https://github.com/thangisme/notes.git synced 2024-10-31 22:27:22 -04:00
notes/node_modules/error-ex/index.js
Patrick Marsceill b7b0d0d7bf
Initial commit
2017-03-09 13:16:08 -05:00

116 lines
2.2 KiB
JavaScript

'use strict';
var util = require('util');
var isArrayish = require('is-arrayish');
var errorEx = function errorEx(name, properties) {
if (!name || name.constructor !== String) {
properties = name || {};
name = Error.name;
}
var errorExError = function ErrorEXError(message) {
if (!this) {
return new ErrorEXError(message);
}
message = message instanceof Error
? message.message
: (message || this.message);
Error.call(this, message);
Error.captureStackTrace(this, errorExError);
this.name = name;
delete this.message;
Object.defineProperty(this, 'message', {
configurable: true,
enumerable: false,
get: function () {
var newMessage = message.split(/\r?\n/g);
for (var key in properties) {
if (properties.hasOwnProperty(key) && 'message' in properties[key]) {
newMessage = properties[key].message(this[key], newMessage) ||
newMessage;
if (!isArrayish(newMessage)) {
newMessage = [newMessage];
}
}
}
return newMessage.join('\n');
},
set: function (v) {
message = v;
}
});
var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack');
var stackGetter = stackDescriptor.get;
stackDescriptor.get = function () {
var stack = stackGetter.call(this).split(/\r?\n+/g);
var lineCount = 1;
for (var key in properties) {
if (!properties.hasOwnProperty(key)) {
continue;
}
var modifier = properties[key];
if ('line' in modifier) {
var line = modifier.line(this[key]);
if (line) {
stack.splice(lineCount, 0, ' ' + line);
}
}
if ('stack' in modifier) {
modifier.stack(this[key], stack);
}
}
return stack.join('\n');
};
Object.defineProperty(this, 'stack', stackDescriptor);
};
util.inherits(errorExError, Error);
return errorExError;
};
errorEx.append = function (str, def) {
return {
message: function (v, message) {
v = v || def;
if (v) {
message[0] += ' ' + str.replace('%s', v.toString());
}
return message;
}
};
};
errorEx.line = function (str, def) {
return {
line: function (v) {
v = v || def;
if (v) {
return str.replace('%s', v.toString());
}
return null;
}
};
};
module.exports = errorEx;