UNPKG

1.75 kBJavaScriptView Raw
1'use strict';
2
3var _ = require('lodash');
4
5function format(message, args) {
6 return message
7 .replace('{0}', args[0])
8 .replace('{1}', args[1])
9 .replace('{2}', args[2]);
10}
11var traverseNode = function(parent, errorDefinition) {
12 var NodeError = function() {
13 if (_.isString(errorDefinition.message)) {
14 this.message = format(errorDefinition.message, arguments);
15 } else if (_.isFunction(errorDefinition.message)) {
16 this.message = errorDefinition.message.apply(null, arguments);
17 } else {
18 throw new Error('Invalid error definition for ' + errorDefinition.name);
19 }
20 this.stack = this.message + '\n' + (new Error()).stack;
21 };
22 NodeError.prototype = Object.create(parent.prototype);
23 NodeError.prototype.name = parent.prototype.name + errorDefinition.name;
24 parent[errorDefinition.name] = NodeError;
25 if (errorDefinition.errors) {
26 childDefinitions(NodeError, errorDefinition.errors);
27 }
28 return NodeError;
29};
30
31/* jshint latedef: false */
32var childDefinitions = function(parent, childDefinitions) {
33 _.each(childDefinitions, function(childDefinition) {
34 traverseNode(parent, childDefinition);
35 });
36};
37/* jshint latedef: true */
38
39var traverseRoot = function(parent, errorsDefinition) {
40 childDefinitions(parent, errorsDefinition);
41 return parent;
42};
43
44
45var bitcore = {};
46bitcore.Error = function() {
47 this.message = 'Internal error';
48 this.stack = this.message + '\n' + (new Error()).stack;
49};
50bitcore.Error.prototype = Object.create(Error.prototype);
51bitcore.Error.prototype.name = 'bitcore.Error';
52
53
54var data = require('./spec');
55traverseRoot(bitcore.Error, data);
56
57module.exports = bitcore.Error;
58
59module.exports.extend = function(spec) {
60 return traverseNode(bitcore.Error, spec);
61};