errors.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. module.metadata = {
  6. "stability": "deprecated"
  7. };
  8. function logToConsole(e) {
  9. console.exception(e);
  10. }
  11. var catchAndLog = exports.catchAndLog = function(callback,
  12. defaultResponse,
  13. logException) {
  14. if (!logException)
  15. logException = logToConsole;
  16. return function() {
  17. try {
  18. return callback.apply(this, arguments);
  19. } catch (e) {
  20. logException(e);
  21. return defaultResponse;
  22. }
  23. };
  24. };
  25. exports.catchAndLogProps = function catchAndLogProps(object,
  26. props,
  27. defaultResponse,
  28. logException) {
  29. if (typeof(props) == "string")
  30. props = [props];
  31. props.forEach(
  32. function(property) {
  33. object[property] = catchAndLog(object[property],
  34. defaultResponse,
  35. logException);
  36. });
  37. };
  38. /**
  39. * Catch and return an exception while calling the callback. If the callback
  40. * doesn't throw, return the return value of the callback in a way that makes it
  41. * possible to distinguish between a return value and an exception.
  42. *
  43. * This function is useful when you need to pass the result of a call across
  44. * a process boundary (across which exceptions don't propagate). It probably
  45. * doesn't need to be factored out into this module, since it is only used by
  46. * a single caller, but putting it here works around bug 625560.
  47. */
  48. exports.catchAndReturn = function(callback) {
  49. return function() {
  50. try {
  51. return { returnValue: callback.apply(this, arguments) };
  52. }
  53. catch (exception) {
  54. return { exception: exception };
  55. }
  56. };
  57. };