1 | 'use strict';
|
2 |
|
3 | var _ = require('lodash');
|
4 |
|
5 | function format(message, args) {
|
6 | return message
|
7 | .replace('{0}', args[0])
|
8 | .replace('{1}', args[1])
|
9 | .replace('{2}', args[2]);
|
10 | }
|
11 | var 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 |
|
32 | var childDefinitions = function(parent, childDefinitions) {
|
33 | _.each(childDefinitions, function(childDefinition) {
|
34 | traverseNode(parent, childDefinition);
|
35 | });
|
36 | };
|
37 |
|
38 |
|
39 | var traverseRoot = function(parent, errorsDefinition) {
|
40 | childDefinitions(parent, errorsDefinition);
|
41 | return parent;
|
42 | };
|
43 |
|
44 |
|
45 | var bitcore = {};
|
46 | bitcore.Error = function() {
|
47 | this.message = 'Internal error';
|
48 | this.stack = this.message + '\n' + (new Error()).stack;
|
49 | };
|
50 | bitcore.Error.prototype = Object.create(Error.prototype);
|
51 | bitcore.Error.prototype.name = 'bitcore.Error';
|
52 |
|
53 |
|
54 | var data = require('./spec');
|
55 | traverseRoot(bitcore.Error, data);
|
56 |
|
57 | module.exports = bitcore.Error;
|
58 |
|
59 | module.exports.extend = function(spec) {
|
60 | return traverseNode(bitcore.Error, spec);
|
61 | };
|