You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

528 lines
21 KiB

  1. # verror: rich JavaScript errors
  2. This module provides several classes in support of Joyent's [Best Practices for
  3. Error Handling in Node.js](http://www.joyent.com/developers/node/design/errors).
  4. If you find any of the behavior here confusing or surprising, check out that
  5. document first.
  6. The error classes here support:
  7. * printf-style arguments for the message
  8. * chains of causes
  9. * properties to provide extra information about the error
  10. * creating your own subclasses that support all of these
  11. The classes here are:
  12. * **VError**, for chaining errors while preserving each one's error message.
  13. This is useful in servers and command-line utilities when you want to
  14. propagate an error up a call stack, but allow various levels to add their own
  15. context. See examples below.
  16. * **WError**, for wrapping errors while hiding the lower-level messages from the
  17. top-level error. This is useful for API endpoints where you don't want to
  18. expose internal error messages, but you still want to preserve the error chain
  19. for logging and debugging.
  20. * **SError**, which is just like VError but interprets printf-style arguments
  21. more strictly.
  22. * **MultiError**, which is just an Error that encapsulates one or more other
  23. errors. (This is used for parallel operations that return several errors.)
  24. # Quick start
  25. First, install the package:
  26. npm install verror
  27. If nothing else, you can use VError as a drop-in replacement for the built-in
  28. JavaScript Error class, with the addition of printf-style messages:
  29. ```javascript
  30. var err = new VError('missing file: "%s"', '/etc/passwd');
  31. console.log(err.message);
  32. ```
  33. This prints:
  34. missing file: "/etc/passwd"
  35. You can also pass a `cause` argument, which is any other Error object:
  36. ```javascript
  37. var fs = require('fs');
  38. var filename = '/nonexistent';
  39. fs.stat(filename, function (err1) {
  40. var err2 = new VError(err1, 'stat "%s"', filename);
  41. console.error(err2.message);
  42. });
  43. ```
  44. This prints out:
  45. stat "/nonexistent": ENOENT, stat '/nonexistent'
  46. which resembles how Unix programs typically report errors:
  47. $ sort /nonexistent
  48. sort: open failed: /nonexistent: No such file or directory
  49. To match the Unixy feel, when you print out the error, just prepend the
  50. program's name to the VError's `message`. Or just call
  51. [node-cmdutil.fail(your_verror)](https://github.com/joyent/node-cmdutil), which
  52. does this for you.
  53. You can get the next-level Error using `err.cause()`:
  54. ```javascript
  55. console.error(err2.cause().message);
  56. ```
  57. prints:
  58. ENOENT, stat '/nonexistent'
  59. Of course, you can chain these as many times as you want, and it works with any
  60. kind of Error:
  61. ```javascript
  62. var err1 = new Error('No such file or directory');
  63. var err2 = new VError(err1, 'failed to stat "%s"', '/junk');
  64. var err3 = new VError(err2, 'request failed');
  65. console.error(err3.message);
  66. ```
  67. This prints:
  68. request failed: failed to stat "/junk": No such file or directory
  69. The idea is that each layer in the stack annotates the error with a description
  70. of what it was doing. The end result is a message that explains what happened
  71. at each level.
  72. You can also decorate Error objects with additional information so that callers
  73. can not only handle each kind of error differently, but also construct their own
  74. error messages (e.g., to localize them, format them, group them by type, and so
  75. on). See the example below.
  76. # Deeper dive
  77. The two main goals for VError are:
  78. * **Make it easy to construct clear, complete error messages intended for
  79. people.** Clear error messages greatly improve both user experience and
  80. debuggability, so we wanted to make it easy to build them. That's why the
  81. constructor takes printf-style arguments.
  82. * **Make it easy to construct objects with programmatically-accessible
  83. metadata** (which we call _informational properties_). Instead of just saying
  84. "connection refused while connecting to 192.168.1.2:80", you can add
  85. properties like `"ip": "192.168.1.2"` and `"tcpPort": 80`. This can be used
  86. for feeding into monitoring systems, analyzing large numbers of Errors (as
  87. from a log file), or localizing error messages.
  88. To really make this useful, it also needs to be easy to compose Errors:
  89. higher-level code should be able to augment the Errors reported by lower-level
  90. code to provide a more complete description of what happened. Instead of saying
  91. "connection refused", you can say "operation X failed: connection refused".
  92. That's why VError supports `causes`.
  93. In order for all this to work, programmers need to know that it's generally safe
  94. to wrap lower-level Errors with higher-level ones. If you have existing code
  95. that handles Errors produced by a library, you should be able to wrap those
  96. Errors with a VError to add information without breaking the error handling
  97. code. There are two obvious ways that this could break such consumers:
  98. * The error's name might change. People typically use `name` to determine what
  99. kind of Error they've got. To ensure compatibility, you can create VErrors
  100. with custom names, but this approach isn't great because it prevents you from
  101. representing complex failures. For this reason, VError provides
  102. `findCauseByName`, which essentially asks: does this Error _or any of its
  103. causes_ have this specific type? If error handling code uses
  104. `findCauseByName`, then subsystems can construct very specific causal chains
  105. for debuggability and still let people handle simple cases easily. There's an
  106. example below.
  107. * The error's properties might change. People often hang additional properties
  108. off of Error objects. If we wrap an existing Error in a new Error, those
  109. properties would be lost unless we copied them. But there are a variety of
  110. both standard and non-standard Error properties that should _not_ be copied in
  111. this way: most obviously `name`, `message`, and `stack`, but also `fileName`,
  112. `lineNumber`, and a few others. Plus, it's useful for some Error subclasses
  113. to have their own private properties -- and there'd be no way to know whether
  114. these should be copied. For these reasons, VError first-classes these
  115. information properties. You have to provide them in the constructor, you can
  116. only fetch them with the `info()` function, and VError takes care of making
  117. sure properties from causes wind up in the `info()` output.
  118. Let's put this all together with an example from the node-fast RPC library.
  119. node-fast implements a simple RPC protocol for Node programs. There's a server
  120. and client interface, and clients make RPC requests to servers. Let's say the
  121. server fails with an UnauthorizedError with message "user 'bob' is not
  122. authorized". The client wraps all server errors with a FastServerError. The
  123. client also wraps all request errors with a FastRequestError that includes the
  124. name of the RPC call being made. The result of this failed RPC might look like
  125. this:
  126. name: FastRequestError
  127. message: "request failed: server error: user 'bob' is not authorized"
  128. rpcMsgid: <unique identifier for this request>
  129. rpcMethod: GetObject
  130. cause:
  131. name: FastServerError
  132. message: "server error: user 'bob' is not authorized"
  133. cause:
  134. name: UnauthorizedError
  135. message: "user 'bob' is not authorized"
  136. rpcUser: "bob"
  137. When the caller uses `VError.info()`, the information properties are collapsed
  138. so that it looks like this:
  139. message: "request failed: server error: user 'bob' is not authorized"
  140. rpcMsgid: <unique identifier for this request>
  141. rpcMethod: GetObject
  142. rpcUser: "bob"
  143. Taking this apart:
  144. * The error's message is a complete description of the problem. The caller can
  145. report this directly to its caller, which can potentially make its way back to
  146. an end user (if appropriate). It can also be logged.
  147. * The caller can tell that the request failed on the server, rather than as a
  148. result of a client problem (e.g., failure to serialize the request), a
  149. transport problem (e.g., failure to connect to the server), or something else
  150. (e.g., a timeout). They do this using `findCauseByName('FastServerError')`
  151. rather than checking the `name` field directly.
  152. * If the caller logs this error, the logs can be analyzed to aggregate
  153. errors by cause, by RPC method name, by user, or whatever. Or the
  154. error can be correlated with other events for the same rpcMsgid.
  155. * It wasn't very hard for any part of the code to contribute to this Error.
  156. Each part of the stack has just a few lines to provide exactly what it knows,
  157. with very little boilerplate.
  158. It's not expected that you'd use these complex forms all the time. Despite
  159. supporting the complex case above, you can still just do:
  160. new VError("my service isn't working");
  161. for the simple cases.
  162. # Reference: VError, WError, SError
  163. VError, WError, and SError are convenient drop-in replacements for `Error` that
  164. support printf-style arguments, first-class causes, informational properties,
  165. and other useful features.
  166. ## Constructors
  167. The VError constructor has several forms:
  168. ```javascript
  169. /*
  170. * This is the most general form. You can specify any supported options
  171. * (including "cause" and "info") this way.
  172. */
  173. new VError(options, sprintf_args...)
  174. /*
  175. * This is a useful shorthand when the only option you need is "cause".
  176. */
  177. new VError(cause, sprintf_args...)
  178. /*
  179. * This is a useful shorthand when you don't need any options at all.
  180. */
  181. new VError(sprintf_args...)
  182. ```
  183. All of these forms construct a new VError that behaves just like the built-in
  184. JavaScript `Error` class, with some additional methods described below.
  185. In the first form, `options` is a plain object with any of the following
  186. optional properties:
  187. Option name | Type | Meaning
  188. ---------------- | ---------------- | -------
  189. `name` | string | Describes what kind of error this is. This is intended for programmatic use to distinguish between different kinds of errors. Note that in modern versions of Node.js, this name is ignored in the `stack` property value, but callers can still use the `name` property to get at it.
  190. `cause` | any Error object | Indicates that the new error was caused by `cause`. See `cause()` below. If unspecified, the cause will be `null`.
  191. `strict` | boolean | If true, then `null` and `undefined` values in `sprintf_args` are passed through to `sprintf()`. Otherwise, these are replaced with the strings `'null'`, and '`undefined`', respectively.
  192. `constructorOpt` | function | If specified, then the stack trace for this error ends at function `constructorOpt`. Functions called by `constructorOpt` will not show up in the stack. This is useful when this class is subclassed.
  193. `info` | object | Specifies arbitrary informational properties that are available through the `VError.info(err)` static class method. See that method for details.
  194. The second form is equivalent to using the first form with the specified `cause`
  195. as the error's cause. This form is distinguished from the first form because
  196. the first argument is an Error.
  197. The third form is equivalent to using the first form with all default option
  198. values. This form is distinguished from the other forms because the first
  199. argument is not an object or an Error.
  200. The `WError` constructor is used exactly the same way as the `VError`
  201. constructor. The `SError` constructor is also used the same way as the
  202. `VError` constructor except that in all cases, the `strict` property is
  203. overriden to `true.
  204. ## Public properties
  205. `VError`, `WError`, and `SError` all provide the same public properties as
  206. JavaScript's built-in Error objects.
  207. Property name | Type | Meaning
  208. ------------- | ------ | -------
  209. `name` | string | Programmatically-usable name of the error.
  210. `message` | string | Human-readable summary of the failure. Programmatically-accessible details are provided through `VError.info(err)` class method.
  211. `stack` | string | Human-readable stack trace where the Error was constructed.
  212. For all of these classes, the printf-style arguments passed to the constructor
  213. are processed with `sprintf()` to form a message. For `WError`, this becomes
  214. the complete `message` property. For `SError` and `VError`, this message is
  215. prepended to the message of the cause, if any (with a suitable separator), and
  216. the result becomes the `message` property.
  217. The `stack` property is managed entirely by the underlying JavaScript
  218. implementation. It's generally implemented using a getter function because
  219. constructing the human-readable stack trace is somewhat expensive.
  220. ## Class methods
  221. The following methods are defined on the `VError` class and as exported
  222. functions on the `verror` module. They're defined this way rather than using
  223. methods on VError instances so that they can be used on Errors not created with
  224. `VError`.
  225. ### `VError.cause(err)`
  226. The `cause()` function returns the next Error in the cause chain for `err`, or
  227. `null` if there is no next error. See the `cause` argument to the constructor.
  228. Errors can have arbitrarily long cause chains. You can walk the `cause` chain
  229. by invoking `VError.cause(err)` on each subsequent return value. If `err` is
  230. not a `VError`, the cause is `null`.
  231. ### `VError.info(err)`
  232. Returns an object with all of the extra error information that's been associated
  233. with this Error and all of its causes. These are the properties passed in using
  234. the `info` option to the constructor. Properties not specified in the
  235. constructor for this Error are implicitly inherited from this error's cause.
  236. These properties are intended to provide programmatically-accessible metadata
  237. about the error. For an error that indicates a failure to resolve a DNS name,
  238. informational properties might include the DNS name to be resolved, or even the
  239. list of resolvers used to resolve it. The values of these properties should
  240. generally be plain objects (i.e., consisting only of null, undefined, numbers,
  241. booleans, strings, and objects and arrays containing only other plain objects).
  242. ### `VError.fullStack(err)`
  243. Returns a string containing the full stack trace, with all nested errors recursively
  244. reported as `'caused by:' + err.stack`.
  245. ### `VError.findCauseByName(err, name)`
  246. The `findCauseByName()` function traverses the cause chain for `err`, looking
  247. for an error whose `name` property matches the passed in `name` value. If no
  248. match is found, `null` is returned.
  249. If all you want is to know _whether_ there's a cause (and you don't care what it
  250. is), you can use `VError.hasCauseWithName(err, name)`.
  251. If a vanilla error or a non-VError error is passed in, then there is no cause
  252. chain to traverse. In this scenario, the function will check the `name`
  253. property of only `err`.
  254. ### `VError.hasCauseWithName(err, name)`
  255. Returns true if and only if `VError.findCauseByName(err, name)` would return
  256. a non-null value. This essentially determines whether `err` has any cause in
  257. its cause chain that has name `name`.
  258. ### `VError.errorFromList(errors)`
  259. Given an array of Error objects (possibly empty), return a single error
  260. representing the whole collection of errors. If the list has:
  261. * 0 elements, returns `null`
  262. * 1 element, returns the sole error
  263. * more than 1 element, returns a MultiError referencing the whole list
  264. This is useful for cases where an operation may produce any number of errors,
  265. and you ultimately want to implement the usual `callback(err)` pattern. You can
  266. accumulate the errors in an array and then invoke
  267. `callback(VError.errorFromList(errors))` when the operation is complete.
  268. ### `VError.errorForEach(err, func)`
  269. Convenience function for iterating an error that may itself be a MultiError.
  270. In all cases, `err` must be an Error. If `err` is a MultiError, then `func` is
  271. invoked as `func(errorN)` for each of the underlying errors of the MultiError.
  272. If `err` is any other kind of error, `func` is invoked once as `func(err)`. In
  273. all cases, `func` is invoked synchronously.
  274. This is useful for cases where an operation may produce any number of warnings
  275. that may be encapsulated with a MultiError -- but may not be.
  276. This function does not iterate an error's cause chain.
  277. ## Examples
  278. The "Demo" section above covers several basic cases. Here's a more advanced
  279. case:
  280. ```javascript
  281. var err1 = new VError('something bad happened');
  282. /* ... */
  283. var err2 = new VError({
  284. 'name': 'ConnectionError',
  285. 'cause': err1,
  286. 'info': {
  287. 'errno': 'ECONNREFUSED',
  288. 'remote_ip': '127.0.0.1',
  289. 'port': 215
  290. }
  291. }, 'failed to connect to "%s:%d"', '127.0.0.1', 215);
  292. console.log(err2.message);
  293. console.log(err2.name);
  294. console.log(VError.info(err2));
  295. console.log(err2.stack);
  296. ```
  297. This outputs:
  298. failed to connect to "127.0.0.1:215": something bad happened
  299. ConnectionError
  300. { errno: 'ECONNREFUSED', remote_ip: '127.0.0.1', port: 215 }
  301. ConnectionError: failed to connect to "127.0.0.1:215": something bad happened
  302. at Object.<anonymous> (/home/dap/node-verror/examples/info.js:5:12)
  303. at Module._compile (module.js:456:26)
  304. at Object.Module._extensions..js (module.js:474:10)
  305. at Module.load (module.js:356:32)
  306. at Function.Module._load (module.js:312:12)
  307. at Function.Module.runMain (module.js:497:10)
  308. at startup (node.js:119:16)
  309. at node.js:935:3
  310. Information properties are inherited up the cause chain, with values at the top
  311. of the chain overriding same-named values lower in the chain. To continue that
  312. example:
  313. ```javascript
  314. var err3 = new VError({
  315. 'name': 'RequestError',
  316. 'cause': err2,
  317. 'info': {
  318. 'errno': 'EBADREQUEST'
  319. }
  320. }, 'request failed');
  321. console.log(err3.message);
  322. console.log(err3.name);
  323. console.log(VError.info(err3));
  324. console.log(err3.stack);
  325. ```
  326. This outputs:
  327. request failed: failed to connect to "127.0.0.1:215": something bad happened
  328. RequestError
  329. { errno: 'EBADREQUEST', remote_ip: '127.0.0.1', port: 215 }
  330. RequestError: request failed: failed to connect to "127.0.0.1:215": something bad happened
  331. at Object.<anonymous> (/home/dap/node-verror/examples/info.js:20:12)
  332. at Module._compile (module.js:456:26)
  333. at Object.Module._extensions..js (module.js:474:10)
  334. at Module.load (module.js:356:32)
  335. at Function.Module._load (module.js:312:12)
  336. at Function.Module.runMain (module.js:497:10)
  337. at startup (node.js:119:16)
  338. at node.js:935:3
  339. You can also print the complete stack trace of combined `Error`s by using
  340. `VError.fullStack(err).`
  341. ```javascript
  342. var err1 = new VError('something bad happened');
  343. /* ... */
  344. var err2 = new VError(err1, 'something really bad happened here');
  345. console.log(VError.fullStack(err2));
  346. ```
  347. This outputs:
  348. VError: something really bad happened here: something bad happened
  349. at Object.<anonymous> (/home/dap/node-verror/examples/fullStack.js:5:12)
  350. at Module._compile (module.js:409:26)
  351. at Object.Module._extensions..js (module.js:416:10)
  352. at Module.load (module.js:343:32)
  353. at Function.Module._load (module.js:300:12)
  354. at Function.Module.runMain (module.js:441:10)
  355. at startup (node.js:139:18)
  356. at node.js:968:3
  357. caused by: VError: something bad happened
  358. at Object.<anonymous> (/home/dap/node-verror/examples/fullStack.js:3:12)
  359. at Module._compile (module.js:409:26)
  360. at Object.Module._extensions..js (module.js:416:10)
  361. at Module.load (module.js:343:32)
  362. at Function.Module._load (module.js:300:12)
  363. at Function.Module.runMain (module.js:441:10)
  364. at startup (node.js:139:18)
  365. at node.js:968:3
  366. `VError.fullStack` is also safe to use on regular `Error`s, so feel free to use
  367. it whenever you need to extract the stack trace from an `Error`, regardless if
  368. it's a `VError` or not.
  369. # Reference: MultiError
  370. MultiError is an Error class that represents a group of Errors. This is used
  371. when you logically need to provide a single Error, but you want to preserve
  372. information about multiple underying Errors. A common case is when you execute
  373. several operations in parallel and some of them fail.
  374. MultiErrors are constructed as:
  375. ```javascript
  376. new MultiError(error_list)
  377. ```
  378. `error_list` is an array of at least one `Error` object.
  379. The cause of the MultiError is the first error provided. None of the other
  380. `VError` options are supported. The `message` for a MultiError consists the
  381. `message` from the first error, prepended with a message indicating that there
  382. were other errors.
  383. For example:
  384. ```javascript
  385. err = new MultiError([
  386. new Error('failed to resolve DNS name "abc.example.com"'),
  387. new Error('failed to resolve DNS name "def.example.com"'),
  388. ]);
  389. console.error(err.message);
  390. ```
  391. outputs:
  392. first of 2 errors: failed to resolve DNS name "abc.example.com"
  393. See the convenience function `VError.errorFromList`, which is sometimes simpler
  394. to use than this constructor.
  395. ## Public methods
  396. ### `errors()`
  397. Returns an array of the errors used to construct this MultiError.
  398. # Contributing
  399. See separate [contribution guidelines](CONTRIBUTING.md).