PageRenderTime 76ms CodeModel.GetById 34ms app.highlight 4ms RepoModel.GetById 36ms app.codeStats 0ms

/src/error.js

https://github.com/devildeveloper/usps-webtools
JavaScript | 51 lines | 28 code | 8 blank | 15 comment | 4 complexity | 92404fddb75e6825f1f0c96ec5d372ae MD5 | raw file
 1/**
 2    Custom USPS Webtools error
 3    Inspiration: http://www.devthought.com/2011/12/22/a-string-is-not-an-error/
 4
 5    Examples:
 6        new USPSError('Error Message');
 7        new USPSError('Error Message', err);
 8
 9    If creating an error instance with a string, note that the stack trace will be that of where the error was initialized
10    If extending a native error (by passing it as second argument) then trace will be accurate, keys copied over, and original message & name will be copied to the 'original' attribute
11    If extending a non-native error (string or object) then the result will be similar to the first case, but the 'original' attribute will be equal to the non-native error
12
13    @param {String} msg The relevant error message
14    @param {Error|String|Object} [original] The original error being extended
15*/
16function USPSError(msg) {
17  var key;
18
19  Error.call(this);
20
21  for (var i = 1, l = arguments.length; i < l; i++) {
22    extendError(this, arguments[i]);
23  }
24
25  if (!this.original) {
26    Error.captureStackTrace(this, arguments.callee);
27  }
28
29  this.name = 'USPS Webtools Error',
30  this.message = typeof msg === 'string' ? msg : 'An error occurred';
31}
32USPSError.prototype.__proto__ = Error.prototype;
33
34USPSError.prototype.toString = function() {
35  return JSON.stringify(this);
36};
37
38function extendError(err, additions) {
39  for (var key in additions) {
40    err[key] = additions[key];
41  }
42
43  if (additions instanceof Error) {
44    err.original = {
45      message: additions.message,
46      name: additions.name
47    };
48  }
49}
50
51module.exports = USPSError;