PageRenderTime 50ms CodeModel.GetById 23ms RepoModel.GetById 1ms 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. Examples:
  5. new USPSError('Error Message');
  6. new USPSError('Error Message', err);
  7. If creating an error instance with a string, note that the stack trace will be that of where the error was initialized
  8. 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
  9. 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
  10. @param {String} msg The relevant error message
  11. @param {Error|String|Object} [original] The original error being extended
  12. */
  13. function USPSError(msg) {
  14. var key;
  15. Error.call(this);
  16. for (var i = 1, l = arguments.length; i < l; i++) {
  17. extendError(this, arguments[i]);
  18. }
  19. if (!this.original) {
  20. Error.captureStackTrace(this, arguments.callee);
  21. }
  22. this.name = 'USPS Webtools Error',
  23. this.message = typeof msg === 'string' ? msg : 'An error occurred';
  24. }
  25. USPSError.prototype.__proto__ = Error.prototype;
  26. USPSError.prototype.toString = function() {
  27. return JSON.stringify(this);
  28. };
  29. function extendError(err, additions) {
  30. for (var key in additions) {
  31. err[key] = additions[key];
  32. }
  33. if (additions instanceof Error) {
  34. err.original = {
  35. message: additions.message,
  36. name: additions.name
  37. };
  38. }
  39. }
  40. module.exports = USPSError;