verror.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. /*
  2. * verror.js: richer JavaScript errors
  3. */
  4. var mod_assertplus = require('assert-plus');
  5. var mod_util = require('util');
  6. var mod_extsprintf = require('extsprintf');
  7. var mod_isError = require('core-util-is').isError;
  8. var sprintf = mod_extsprintf.sprintf;
  9. /*
  10. * Public interface
  11. */
  12. /* So you can 'var VError = require('verror')' */
  13. module.exports = VError;
  14. /* For compatibility */
  15. VError.VError = VError;
  16. /* Other exported classes */
  17. VError.SError = SError;
  18. VError.WError = WError;
  19. VError.MultiError = MultiError;
  20. /*
  21. * Common function used to parse constructor arguments for VError, WError, and
  22. * SError. Named arguments to this function:
  23. *
  24. * strict force strict interpretation of sprintf arguments, even
  25. * if the options in "argv" don't say so
  26. *
  27. * argv error's constructor arguments, which are to be
  28. * interpreted as described in README.md. For quick
  29. * reference, "argv" has one of the following forms:
  30. *
  31. * [ sprintf_args... ] (argv[0] is a string)
  32. * [ cause, sprintf_args... ] (argv[0] is an Error)
  33. * [ options, sprintf_args... ] (argv[0] is an object)
  34. *
  35. * This function normalizes these forms, producing an object with the following
  36. * properties:
  37. *
  38. * options equivalent to "options" in third form. This will never
  39. * be a direct reference to what the caller passed in
  40. * (i.e., it may be a shallow copy), so it can be freely
  41. * modified.
  42. *
  43. * shortmessage result of sprintf(sprintf_args), taking options.strict
  44. * into account as described in README.md.
  45. */
  46. function parseConstructorArguments(args)
  47. {
  48. var argv, options, sprintf_args, shortmessage, k;
  49. mod_assertplus.object(args, 'args');
  50. mod_assertplus.bool(args.strict, 'args.strict');
  51. mod_assertplus.array(args.argv, 'args.argv');
  52. argv = args.argv;
  53. /*
  54. * First, figure out which form of invocation we've been given.
  55. */
  56. if (argv.length === 0) {
  57. options = {};
  58. sprintf_args = [];
  59. } else if (mod_isError(argv[0])) {
  60. options = { 'cause': argv[0] };
  61. sprintf_args = argv.slice(1);
  62. } else if (typeof (argv[0]) === 'object') {
  63. options = {};
  64. for (k in argv[0]) {
  65. options[k] = argv[0][k];
  66. }
  67. sprintf_args = argv.slice(1);
  68. } else {
  69. mod_assertplus.string(argv[0],
  70. 'first argument to VError, SError, or WError ' +
  71. 'constructor must be a string, object, or Error');
  72. options = {};
  73. sprintf_args = argv;
  74. }
  75. /*
  76. * Now construct the error's message.
  77. *
  78. * extsprintf (which we invoke here with our caller's arguments in order
  79. * to construct this Error's message) is strict in its interpretation of
  80. * values to be processed by the "%s" specifier. The value passed to
  81. * extsprintf must actually be a string or something convertible to a
  82. * String using .toString(). Passing other values (notably "null" and
  83. * "undefined") is considered a programmer error. The assumption is
  84. * that if you actually want to print the string "null" or "undefined",
  85. * then that's easy to do that when you're calling extsprintf; on the
  86. * other hand, if you did NOT want that (i.e., there's actually a bug
  87. * where the program assumes some variable is non-null and tries to
  88. * print it, which might happen when constructing a packet or file in
  89. * some specific format), then it's better to stop immediately than
  90. * produce bogus output.
  91. *
  92. * However, sometimes the bug is only in the code calling VError, and a
  93. * programmer might prefer to have the error message contain "null" or
  94. * "undefined" rather than have the bug in the error path crash the
  95. * program (making the first bug harder to identify). For that reason,
  96. * by default VError converts "null" or "undefined" arguments to their
  97. * string representations and passes those to extsprintf. Programmers
  98. * desiring the strict behavior can use the SError class or pass the
  99. * "strict" option to the VError constructor.
  100. */
  101. mod_assertplus.object(options);
  102. if (!options.strict && !args.strict) {
  103. sprintf_args = sprintf_args.map(function (a) {
  104. return (a === null ? 'null' :
  105. a === undefined ? 'undefined' : a);
  106. });
  107. }
  108. if (sprintf_args.length === 0) {
  109. shortmessage = '';
  110. } else {
  111. shortmessage = sprintf.apply(null, sprintf_args);
  112. }
  113. return ({
  114. 'options': options,
  115. 'shortmessage': shortmessage
  116. });
  117. }
  118. /*
  119. * See README.md for reference documentation.
  120. */
  121. function VError()
  122. {
  123. var args, obj, parsed, cause, ctor, message, k;
  124. args = Array.prototype.slice.call(arguments, 0);
  125. /*
  126. * This is a regrettable pattern, but JavaScript's built-in Error class
  127. * is defined to work this way, so we allow the constructor to be called
  128. * without "new".
  129. */
  130. if (!(this instanceof VError)) {
  131. obj = Object.create(VError.prototype);
  132. VError.apply(obj, arguments);
  133. return (obj);
  134. }
  135. /*
  136. * For convenience and backwards compatibility, we support several
  137. * different calling forms. Normalize them here.
  138. */
  139. parsed = parseConstructorArguments({
  140. 'argv': args,
  141. 'strict': false
  142. });
  143. /*
  144. * If we've been given a name, apply it now.
  145. */
  146. if (parsed.options.name) {
  147. mod_assertplus.string(parsed.options.name,
  148. 'error\'s "name" must be a string');
  149. this.name = parsed.options.name;
  150. }
  151. /*
  152. * For debugging, we keep track of the original short message (attached
  153. * this Error particularly) separately from the complete message (which
  154. * includes the messages of our cause chain).
  155. */
  156. this.jse_shortmsg = parsed.shortmessage;
  157. message = parsed.shortmessage;
  158. /*
  159. * If we've been given a cause, record a reference to it and update our
  160. * message appropriately.
  161. */
  162. cause = parsed.options.cause;
  163. if (cause) {
  164. mod_assertplus.ok(mod_isError(cause), 'cause is not an Error');
  165. this.jse_cause = cause;
  166. if (!parsed.options.skipCauseMessage) {
  167. message += ': ' + cause.message;
  168. }
  169. }
  170. /*
  171. * If we've been given an object with properties, shallow-copy that
  172. * here. We don't want to use a deep copy in case there are non-plain
  173. * objects here, but we don't want to use the original object in case
  174. * the caller modifies it later.
  175. */
  176. this.jse_info = {};
  177. if (parsed.options.info) {
  178. for (k in parsed.options.info) {
  179. this.jse_info[k] = parsed.options.info[k];
  180. }
  181. }
  182. this.message = message;
  183. Error.call(this, message);
  184. if (Error.captureStackTrace) {
  185. ctor = parsed.options.constructorOpt || this.constructor;
  186. Error.captureStackTrace(this, ctor);
  187. }
  188. return (this);
  189. }
  190. mod_util.inherits(VError, Error);
  191. VError.prototype.name = 'VError';
  192. VError.prototype.toString = function ve_toString()
  193. {
  194. var str = (this.hasOwnProperty('name') && this.name ||
  195. this.constructor.name || this.constructor.prototype.name);
  196. if (this.message)
  197. str += ': ' + this.message;
  198. return (str);
  199. };
  200. /*
  201. * This method is provided for compatibility. New callers should use
  202. * VError.cause() instead. That method also uses the saner `null` return value
  203. * when there is no cause.
  204. */
  205. VError.prototype.cause = function ve_cause()
  206. {
  207. var cause = VError.cause(this);
  208. return (cause === null ? undefined : cause);
  209. };
  210. /*
  211. * Static methods
  212. *
  213. * These class-level methods are provided so that callers can use them on
  214. * instances of Errors that are not VErrors. New interfaces should be provided
  215. * only using static methods to eliminate the class of programming mistake where
  216. * people fail to check whether the Error object has the corresponding methods.
  217. */
  218. VError.cause = function (err)
  219. {
  220. mod_assertplus.ok(mod_isError(err), 'err must be an Error');
  221. return (mod_isError(err.jse_cause) ? err.jse_cause : null);
  222. };
  223. VError.info = function (err)
  224. {
  225. var rv, cause, k;
  226. mod_assertplus.ok(mod_isError(err), 'err must be an Error');
  227. cause = VError.cause(err);
  228. if (cause !== null) {
  229. rv = VError.info(cause);
  230. } else {
  231. rv = {};
  232. }
  233. if (typeof (err.jse_info) == 'object' && err.jse_info !== null) {
  234. for (k in err.jse_info) {
  235. rv[k] = err.jse_info[k];
  236. }
  237. }
  238. return (rv);
  239. };
  240. VError.findCauseByName = function (err, name)
  241. {
  242. var cause;
  243. mod_assertplus.ok(mod_isError(err), 'err must be an Error');
  244. mod_assertplus.string(name, 'name');
  245. mod_assertplus.ok(name.length > 0, 'name cannot be empty');
  246. for (cause = err; cause !== null; cause = VError.cause(cause)) {
  247. mod_assertplus.ok(mod_isError(cause));
  248. if (cause.name == name) {
  249. return (cause);
  250. }
  251. }
  252. return (null);
  253. };
  254. VError.hasCauseWithName = function (err, name)
  255. {
  256. return (VError.findCauseByName(err, name) !== null);
  257. };
  258. VError.fullStack = function (err)
  259. {
  260. mod_assertplus.ok(mod_isError(err), 'err must be an Error');
  261. var cause = VError.cause(err);
  262. if (cause) {
  263. return (err.stack + '\ncaused by: ' + VError.fullStack(cause));
  264. }
  265. return (err.stack);
  266. };
  267. VError.errorFromList = function (errors)
  268. {
  269. mod_assertplus.arrayOfObject(errors, 'errors');
  270. if (errors.length === 0) {
  271. return (null);
  272. }
  273. errors.forEach(function (e) {
  274. mod_assertplus.ok(mod_isError(e));
  275. });
  276. if (errors.length == 1) {
  277. return (errors[0]);
  278. }
  279. return (new MultiError(errors));
  280. };
  281. VError.errorForEach = function (err, func)
  282. {
  283. mod_assertplus.ok(mod_isError(err), 'err must be an Error');
  284. mod_assertplus.func(func, 'func');
  285. if (err instanceof MultiError) {
  286. err.errors().forEach(function iterError(e) { func(e); });
  287. } else {
  288. func(err);
  289. }
  290. };
  291. /*
  292. * SError is like VError, but stricter about types. You cannot pass "null" or
  293. * "undefined" as string arguments to the formatter.
  294. */
  295. function SError()
  296. {
  297. var args, obj, parsed, options;
  298. args = Array.prototype.slice.call(arguments, 0);
  299. if (!(this instanceof SError)) {
  300. obj = Object.create(SError.prototype);
  301. SError.apply(obj, arguments);
  302. return (obj);
  303. }
  304. parsed = parseConstructorArguments({
  305. 'argv': args,
  306. 'strict': true
  307. });
  308. options = parsed.options;
  309. VError.call(this, options, '%s', parsed.shortmessage);
  310. return (this);
  311. }
  312. /*
  313. * We don't bother setting SError.prototype.name because once constructed,
  314. * SErrors are just like VErrors.
  315. */
  316. mod_util.inherits(SError, VError);
  317. /*
  318. * Represents a collection of errors for the purpose of consumers that generally
  319. * only deal with one error. Callers can extract the individual errors
  320. * contained in this object, but may also just treat it as a normal single
  321. * error, in which case a summary message will be printed.
  322. */
  323. function MultiError(errors)
  324. {
  325. mod_assertplus.array(errors, 'list of errors');
  326. mod_assertplus.ok(errors.length > 0, 'must be at least one error');
  327. this.ase_errors = errors;
  328. VError.call(this, {
  329. 'cause': errors[0]
  330. }, 'first of %d error%s', errors.length, errors.length == 1 ? '' : 's');
  331. }
  332. mod_util.inherits(MultiError, VError);
  333. MultiError.prototype.name = 'MultiError';
  334. MultiError.prototype.errors = function me_errors()
  335. {
  336. return (this.ase_errors.slice(0));
  337. };
  338. /*
  339. * See README.md for reference details.
  340. */
  341. function WError()
  342. {
  343. var args, obj, parsed, options;
  344. args = Array.prototype.slice.call(arguments, 0);
  345. if (!(this instanceof WError)) {
  346. obj = Object.create(WError.prototype);
  347. WError.apply(obj, args);
  348. return (obj);
  349. }
  350. parsed = parseConstructorArguments({
  351. 'argv': args,
  352. 'strict': false
  353. });
  354. options = parsed.options;
  355. options['skipCauseMessage'] = true;
  356. VError.call(this, options, '%s', parsed.shortmessage);
  357. return (this);
  358. }
  359. mod_util.inherits(WError, VError);
  360. WError.prototype.name = 'WError';
  361. WError.prototype.toString = function we_toString()
  362. {
  363. var str = (this.hasOwnProperty('name') && this.name ||
  364. this.constructor.name || this.constructor.prototype.name);
  365. if (this.message)
  366. str += ': ' + this.message;
  367. if (this.jse_cause && this.jse_cause.message)
  368. str += '; caused by ' + this.jse_cause.toString();
  369. return (str);
  370. };
  371. /*
  372. * For purely historical reasons, WError's cause() function allows you to set
  373. * the cause.
  374. */
  375. WError.prototype.cause = function we_cause(c)
  376. {
  377. if (mod_isError(c))
  378. this.jse_cause = c;
  379. return (this.jse_cause);
  380. };