123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- '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;
|