index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * Copyright(c) dead_horse and other contributors.
  3. * MIT Licensed
  4. *
  5. * Authors:
  6. * dead_horse <dead_horse@qq.com>
  7. * fengmk2 <fengmk2@gmail.com> (http://fengmk2.com)
  8. */
  9. 'use strict';
  10. /**
  11. * Module dependencies.
  12. */
  13. var ready = require('get-ready');
  14. var EventEmitter = require('events').EventEmitter;
  15. var util = require('util');
  16. module.exports = Base;
  17. function Base() {
  18. EventEmitter.call(this);
  19. this.on('error', this.defaultErrorHandler.bind(this));
  20. }
  21. /**
  22. * inherits from EventEmitter
  23. */
  24. util.inherits(Base, EventEmitter);
  25. ready.mixin(Base.prototype);
  26. Base.prototype.defaultErrorHandler = function (err) {
  27. if (this.listeners('error').length > 1) {
  28. // ignore defaultErrorHandler
  29. return;
  30. }
  31. console.error('\n[%s][pid: %s][%s][%s] %s: %s \nError Stack:\n %s',
  32. Date(), process.pid, this.constructor.name, __filename, err.name,
  33. err.message, err.stack);
  34. // try to show addition property on the error object
  35. // e.g.: `err.data = {url: '/foo'};`
  36. var additions = [];
  37. for (var key in err) {
  38. if (key === 'name' || key === 'message') {
  39. continue;
  40. }
  41. additions.push(util.format(' %s: %j', key, err[key]));
  42. }
  43. if (additions.length) {
  44. console.error('Error Additions:\n%s', additions.join('\n'));
  45. }
  46. console.error();
  47. };