index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. "use strict";
  2. // cache a reference to setTimeout, so that our reference won't be stubbed out
  3. // when using fake timers and errors will still get logged
  4. // https://github.com/cjohansen/Sinon.JS/issues/381
  5. var realSetTimeout = setTimeout;
  6. function configureLogger(config) {
  7. config = config || {};
  8. // Function which prints errors.
  9. if (!config.hasOwnProperty("logger")) {
  10. config.logger = function () { };
  11. }
  12. // When set to true, any errors logged will be thrown immediately;
  13. // If set to false, the errors will be thrown in separate execution frame.
  14. if (!config.hasOwnProperty("useImmediateExceptions")) {
  15. config.useImmediateExceptions = true;
  16. }
  17. // wrap realSetTimeout with something we can stub in tests
  18. if (!config.hasOwnProperty("setTimeout")) {
  19. config.setTimeout = realSetTimeout;
  20. }
  21. return function logError(label, e) {
  22. var msg = label + " threw exception: ";
  23. var err = { name: e.name || label, message: e.message || e.toString(), stack: e.stack };
  24. function throwLoggedError() {
  25. err.message = msg + err.message;
  26. throw err;
  27. }
  28. config.logger(msg + "[" + err.name + "] " + err.message);
  29. if (err.stack) {
  30. config.logger(err.stack);
  31. }
  32. if (config.useImmediateExceptions) {
  33. throwLoggedError();
  34. } else {
  35. config.setTimeout(throwLoggedError, 0);
  36. }
  37. };
  38. }
  39. module.exports = configureLogger;