verror
Advanced tools
Comparing version 1.6.1 to 1.7.0
@@ -5,3 +5,3 @@ /* | ||
var mod_assert = require('assert'); | ||
var mod_assertplus = require('assert-plus'); | ||
var mod_util = require('util'); | ||
@@ -11,2 +11,3 @@ | ||
var mod_isError = require('core-util-is').isError; | ||
var sprintf = mod_extsprintf.sprintf; | ||
@@ -27,39 +28,62 @@ /* | ||
/* | ||
* VError([cause], fmt[, arg...]): Like JavaScript's built-in Error class, but | ||
* supports a "cause" argument (another error) and a printf-style message. The | ||
* cause argument can be null or omitted entirely. | ||
* Common function used to parse constructor arguments for VError, WError, and | ||
* SError. Named arguments to this function: | ||
* | ||
* Examples: | ||
* strict force strict interpretation of sprintf arguments, even | ||
* if the options in "argv" don't say so | ||
* | ||
* CODE MESSAGE | ||
* new VError('something bad happened') "something bad happened" | ||
* new VError('missing file: "%s"', file) "missing file: "/etc/passwd" | ||
* with file = '/etc/passwd' | ||
* new VError(err, 'open failed') "open failed: file not found" | ||
* with err.message = 'file not found' | ||
* argv error's constructor arguments, which are to be | ||
* interpreted as described in README.md. For quick | ||
* reference, "argv" has one of the following forms: | ||
* | ||
* [ sprintf_args... ] (argv[0] is a string) | ||
* [ cause, sprintf_args... ] (argv[0] is an Error) | ||
* [ options, sprintf_args... ] (argv[0] is an object) | ||
* | ||
* This function normalizes these forms, producing an object with the following | ||
* properties: | ||
* | ||
* options equivalent to "options" in third form. This will never | ||
* be a direct reference to what the caller passed in | ||
* (i.e., it may be a shallow copy), so it can be freely | ||
* modified. | ||
* | ||
* shortmessage result of sprintf(sprintf_args), taking options.strict | ||
* into account as described in README.md. | ||
*/ | ||
function VError(options) | ||
function parseConstructorArguments(args) | ||
{ | ||
var args, obj, causedBy, ctor, tailmsg; | ||
var argv, options, sprintf_args, shortmessage, k; | ||
mod_assertplus.object(args, 'args'); | ||
mod_assertplus.bool(args.strict, 'args.strict'); | ||
mod_assertplus.array(args.argv, 'args.argv'); | ||
argv = args.argv; | ||
/* | ||
* This is a regrettable pattern, but JavaScript's built-in Error class | ||
* is defined to work this way, so we allow the constructor to be called | ||
* without "new". | ||
* First, figure out which form of invocation we've been given. | ||
*/ | ||
if (!(this instanceof VError)) { | ||
args = Array.prototype.slice.call(arguments, 0); | ||
obj = Object.create(VError.prototype); | ||
VError.apply(obj, arguments); | ||
return (obj); | ||
} | ||
if (mod_isError(options) || typeof (options) === 'object') { | ||
args = Array.prototype.slice.call(arguments, 1); | ||
if (argv.length === 0) { | ||
options = {}; | ||
sprintf_args = []; | ||
} else if (mod_isError(argv[0])) { | ||
options = { 'cause': argv[0] }; | ||
sprintf_args = argv.slice(1); | ||
} else if (typeof (argv[0]) === 'object') { | ||
options = {}; | ||
for (k in argv[0]) { | ||
options[k] = argv[0][k]; | ||
} | ||
sprintf_args = argv.slice(1); | ||
} else { | ||
args = Array.prototype.slice.call(arguments, 0); | ||
options = undefined; | ||
mod_assertplus.string(argv[0], | ||
'first argument to VError, SError, or WError ' + | ||
'constructor must be a string, object, or Error'); | ||
options = {}; | ||
sprintf_args = argv; | ||
} | ||
/* | ||
* Now construct the error's message. | ||
* | ||
* extsprintf (which we invoke here with our caller's arguments in order | ||
@@ -88,4 +112,5 @@ * to construct this Error's message) is strict in its interpretation of | ||
*/ | ||
if (!options || !options.strict) { | ||
args = args.map(function (a) { | ||
mod_assertplus.object(options); | ||
if (!options.strict && !args.strict) { | ||
sprintf_args = sprintf_args.map(function (a) { | ||
return (a === null ? 'null' : | ||
@@ -96,25 +121,92 @@ a === undefined ? 'undefined' : a); | ||
tailmsg = args.length > 0 ? | ||
mod_extsprintf.sprintf.apply(null, args) : ''; | ||
this.jse_shortmsg = tailmsg; | ||
this.jse_summary = tailmsg; | ||
if (sprintf_args.length === 0) { | ||
shortmessage = ''; | ||
} else { | ||
shortmessage = sprintf.apply(null, sprintf_args); | ||
} | ||
if (options) { | ||
causedBy = options.cause; | ||
return ({ | ||
'options': options, | ||
'shortmessage': shortmessage | ||
}); | ||
} | ||
if (!causedBy || !mod_isError(options.cause)) | ||
causedBy = options; | ||
/* | ||
* See README.md for reference documentation. | ||
*/ | ||
function VError() | ||
{ | ||
var args, obj, parsed, cause, ctor, message, k; | ||
if (causedBy && mod_isError(causedBy)) { | ||
this.jse_cause = causedBy; | ||
this.jse_summary += ': ' + causedBy.message; | ||
args = Array.prototype.slice.call(arguments, 0); | ||
/* | ||
* This is a regrettable pattern, but JavaScript's built-in Error class | ||
* is defined to work this way, so we allow the constructor to be called | ||
* without "new". | ||
*/ | ||
if (!(this instanceof VError)) { | ||
obj = Object.create(VError.prototype); | ||
VError.apply(obj, arguments); | ||
return (obj); | ||
} | ||
/* | ||
* For convenience and backwards compatibility, we support several | ||
* different calling forms. Normalize them here. | ||
*/ | ||
parsed = parseConstructorArguments({ | ||
'argv': args, | ||
'strict': false | ||
}); | ||
/* | ||
* If we've been given a name, apply it now. | ||
*/ | ||
if (parsed.options.name) { | ||
mod_assertplus.string(parsed.options.name, | ||
'error\'s "name" must be a string'); | ||
this.name = parsed.options.name; | ||
} | ||
/* | ||
* For debugging, we keep track of the original short message (attached | ||
* this Error particularly) separately from the complete message (which | ||
* includes the messages of our cause chain). | ||
*/ | ||
this.jse_shortmsg = parsed.shortmessage; | ||
message = parsed.shortmessage; | ||
/* | ||
* If we've been given a cause, record a reference to it and update our | ||
* message appropriately. | ||
*/ | ||
cause = parsed.options.cause; | ||
if (cause) { | ||
mod_assertplus.ok(mod_isError(cause), 'cause is not an Error'); | ||
this.jse_cause = cause; | ||
if (!parsed.options.skipCauseMessage) { | ||
message += ': ' + cause.message; | ||
} | ||
} | ||
this.message = this.jse_summary; | ||
Error.call(this, this.jse_summary); | ||
/* | ||
* If we've been given an object with properties, shallow-copy that | ||
* here. We don't want to use a deep copy in case there are non-plain | ||
* objects here, but we don't want to use the original object in case | ||
* the caller modifies it later. | ||
*/ | ||
this.jse_info = {}; | ||
if (parsed.options.info) { | ||
for (k in parsed.options.info) { | ||
this.jse_info[k] = parsed.options.info[k]; | ||
} | ||
} | ||
this.message = message; | ||
Error.call(this, message); | ||
if (Error.captureStackTrace) { | ||
ctor = options ? options.constructorOpt : undefined; | ||
ctor = ctor || arguments.callee; | ||
ctor = parsed.options.constructorOpt || arguments.callee; | ||
Error.captureStackTrace(this, ctor); | ||
@@ -139,37 +231,102 @@ } | ||
/* | ||
* This method is provided for compatibility. New callers should use | ||
* VError.cause() instead. That method also uses the saner `null` return value | ||
* when there is no cause. | ||
*/ | ||
VError.prototype.cause = function ve_cause() | ||
{ | ||
return (this.jse_cause); | ||
var cause = VError.cause(this); | ||
return (cause === null ? undefined : cause); | ||
}; | ||
/* | ||
* Static methods | ||
* | ||
* These class-level methods are provided so that callers can use them on | ||
* instances of Errors that are not VErrors. New interfaces should be provided | ||
* only using static methods to eliminate the class of programming mistake where | ||
* people fail to check whether the Error object has the corresponding methods. | ||
*/ | ||
VError.cause = function (err) | ||
{ | ||
mod_assertplus.ok(mod_isError(err), 'err must be an Error'); | ||
return (mod_isError(err.jse_cause) ? err.jse_cause : null); | ||
}; | ||
VError.info = function (err) | ||
{ | ||
var rv, cause, k; | ||
mod_assertplus.ok(mod_isError(err), 'err must be an Error'); | ||
cause = VError.cause(err); | ||
if (cause !== null) { | ||
rv = VError.info(cause); | ||
} else { | ||
rv = {}; | ||
} | ||
if (typeof (err.jse_info) == 'object' && err.jse_info !== null) { | ||
for (k in err.jse_info) { | ||
rv[k] = err.jse_info[k]; | ||
} | ||
} | ||
return (rv); | ||
}; | ||
VError.findCauseByName = function (err, name) | ||
{ | ||
var cause; | ||
mod_assertplus.ok(mod_isError(err), 'err must be an Error'); | ||
mod_assertplus.string(name); | ||
mod_assertplus.ok(name.length > 0, 'name cannot be empty'); | ||
for (cause = err; cause !== null; cause = VError.cause(cause)) { | ||
mod_assertplus.ok(mod_isError(cause)); | ||
if (cause.name == name) { | ||
return (cause); | ||
} | ||
} | ||
return (null); | ||
}; | ||
/* | ||
* SError is like VError, but stricter about types. You cannot pass "null" or | ||
* "undefined" as string arguments to the formatter. Since SError is only a | ||
* different function, not really a different class, we don't set | ||
* SError.prototype.name. | ||
* "undefined" as string arguments to the formatter. | ||
*/ | ||
function SError() | ||
{ | ||
var fmtargs, opts, key, args; | ||
var args, obj, parsed, options; | ||
opts = {}; | ||
opts.constructorOpt = SError; | ||
args = Array.prototype.slice.call(arguments, 0); | ||
if (!(this instanceof SError)) { | ||
obj = Object.create(SError.prototype); | ||
SError.apply(obj, arguments); | ||
return (obj); | ||
} | ||
if (mod_isError(arguments[0])) { | ||
opts.cause = arguments[0]; | ||
fmtargs = Array.prototype.slice.call(arguments, 1); | ||
} else if (typeof (arguments[0]) == 'object') { | ||
for (key in arguments[0]) | ||
opts[key] = arguments[0][key]; | ||
fmtargs = Array.prototype.slice.call(arguments, 1); | ||
} else { | ||
fmtargs = Array.prototype.slice.call(arguments, 0); | ||
parsed = parseConstructorArguments({ | ||
'argv': args, | ||
'strict': true | ||
}); | ||
options = parsed.options; | ||
if (!options.hasOwnProperty('constructorOpt')) { | ||
options['constructorOpt'] = SError; | ||
} | ||
opts.strict = true; | ||
args = [ opts ].concat(fmtargs); | ||
VError.apply(this, args); | ||
VError.call(this, options, '%s', parsed.shortmessage); | ||
return (this); | ||
} | ||
/* | ||
* We don't bother setting SError.prototype.name because once constructed, | ||
* SErrors are just like VErrors. | ||
*/ | ||
mod_util.inherits(SError, VError); | ||
@@ -186,54 +343,54 @@ | ||
{ | ||
mod_assert.ok(errors.length > 0); | ||
mod_assertplus.array(errors, 'list of errors'); | ||
mod_assertplus.ok(errors.length > 0, 'must be at least one error'); | ||
this.ase_errors = errors; | ||
VError.call(this, errors[0], 'first of %d error%s', | ||
errors.length, errors.length == 1 ? '' : 's'); | ||
VError.call(this, { | ||
'cause': errors[0], | ||
'constructorOpt': MultiError | ||
}, 'first of %d error%s', errors.length, errors.length == 1 ? '' : 's'); | ||
} | ||
mod_util.inherits(MultiError, VError); | ||
MultiError.prototype.name = 'MultiError'; | ||
MultiError.prototype.errors = function me_errors() | ||
{ | ||
return (this.ase_errors.slice(0)); | ||
}; | ||
/* | ||
* Like JavaScript's built-in Error class, but supports a "cause" argument which | ||
* is wrapped, not "folded in" as with VError. Accepts a printf-style message. | ||
* The cause argument can be null. | ||
* See README.md for reference details. | ||
*/ | ||
function WError(options) | ||
function WError() | ||
{ | ||
Error.call(this); | ||
var args, obj, parsed, options; | ||
var args, cause, ctor; | ||
if (typeof (options) === 'object') { | ||
args = Array.prototype.slice.call(arguments, 1); | ||
} else { | ||
args = Array.prototype.slice.call(arguments, 0); | ||
options = undefined; | ||
args = Array.prototype.slice.call(arguments, 0); | ||
if (!(this instanceof WError)) { | ||
obj = Object.create(WError.prototype); | ||
WError.apply(obj, args); | ||
return (obj); | ||
} | ||
if (args.length > 0) { | ||
this.message = mod_extsprintf.sprintf.apply(null, args); | ||
} else { | ||
this.message = ''; | ||
} | ||
parsed = parseConstructorArguments({ | ||
'argv': args, | ||
'strict': false | ||
}); | ||
if (options) { | ||
if (mod_isError(options)) { | ||
cause = options; | ||
} else { | ||
cause = options.cause; | ||
ctor = options.constructorOpt; | ||
} | ||
options = parsed.options; | ||
options['skipCauseMessage'] = true; | ||
if (!options.hasOwnProperty('constructorOpt')) { | ||
options['constructorOpt'] = WError; | ||
} | ||
Error.captureStackTrace(this, ctor || this.constructor); | ||
if (cause) | ||
this.cause(cause); | ||
VError.call(this, options, '%s', parsed.shortmessage); | ||
return (this); | ||
} | ||
mod_util.inherits(WError, Error); | ||
mod_util.inherits(WError, VError); | ||
WError.prototype.name = 'WError'; | ||
WError.prototype.toString = function we_toString() | ||
@@ -245,4 +402,4 @@ { | ||
str += ': ' + this.message; | ||
if (this.we_cause && this.we_cause.message) | ||
str += '; caused by ' + this.we_cause.toString(); | ||
if (this.jse_cause && this.jse_cause.message) | ||
str += '; caused by ' + this.jse_cause.toString(); | ||
@@ -252,8 +409,12 @@ return (str); | ||
/* | ||
* For purely historical reasons, WError's cause() function allows you to set | ||
* the cause. | ||
*/ | ||
WError.prototype.cause = function we_cause(c) | ||
{ | ||
if (mod_isError(c)) | ||
this.we_cause = c; | ||
this.jse_cause = c; | ||
return (this.we_cause); | ||
return (this.jse_cause); | ||
}; |
{ | ||
"name": "verror", | ||
"version": "1.6.1", | ||
"version": "1.7.0", | ||
"description": "richer JavaScript errors", | ||
@@ -11,4 +11,5 @@ "main": "./lib/verror.js", | ||
"dependencies": { | ||
"assert-plus": "^1.0.0", | ||
"core-util-is": "1.0.2", | ||
"extsprintf": "1.2.0" | ||
"extsprintf": "^1.2.0" | ||
}, | ||
@@ -15,0 +16,0 @@ "engines": [ |
431
README.md
@@ -1,32 +0,43 @@ | ||
# verror: richer JavaScript errors | ||
# verror: rich JavaScript errors | ||
This module provides two classes: | ||
This module provides several classes in support of Joyent's [Best Practices for | ||
Error Handling in Node.js](http://www.joyent.com/developers/node/design/errors). | ||
If you find any of the behavior here confusing or surprising, check out that | ||
document first. | ||
* VError, for combining errors while preserving each one's error message, and | ||
* WError, for wrapping errors. | ||
The error classes here support: | ||
Both support printf-style error messages using | ||
[extsprintf](https://github.com/davepacheco/node-extsprintf). | ||
* printf-style arguments for the message | ||
* chains of causes | ||
* properties to provide extra information about the error | ||
* creating your own subclasses that support all of these | ||
## printf-style Error constructor | ||
The classes here are: | ||
At the most basic level, VError is just like JavaScript's Error class, but with | ||
printf-style arguments: | ||
* **VError**, for chaining errors while preserving each one's error message. | ||
This is useful in servers and command-line utilities when you want to | ||
propagate an error up a call stack, but allow various levels to add their own | ||
context. See examples below. | ||
* **WError**, for wrapping errors while hiding the lower-level messages from the | ||
top-level error. This is useful for API endpoints where you don't want to | ||
expose internal error messages, but you still want to preserve the error chain | ||
for logging and debugging. | ||
* **SError**, which is just like VError but interprets printf-style arguments | ||
more strictly. | ||
* **MultiError**, which is just an Error that encapsulates one or more other | ||
errors. (This is used for parallel operations that return several errors.) | ||
```javascript | ||
var VError = require('verror'); | ||
var filename = '/etc/passwd'; | ||
var err = new VError('missing file: "%s"', filename); | ||
console.log(err.message); | ||
``` | ||
# Quick start | ||
This prints: | ||
First, install the package: | ||
missing file: "/etc/passwd" | ||
npm install verror | ||
`err.stack` works the same as for built-in errors: | ||
If nothing else, you can use VError as a drop-in replacement for the built-in | ||
JavaScript Error class, with the addition of printf-style messages: | ||
```javascript | ||
console.log(err.stack); | ||
var err = new VError('missing file: "%s"', '/etc/passwd'); | ||
console.log(err.message); | ||
``` | ||
@@ -37,22 +48,10 @@ | ||
missing file: "/etc/passwd" | ||
at Object.<anonymous> (/Users/dap/node-verror/examples/varargs.js:4:11) | ||
at Module._compile (module.js:449:26) | ||
at Object.Module._extensions..js (module.js:467:10) | ||
at Module.load (module.js:356:32) | ||
at Function.Module._load (module.js:312:12) | ||
at Module.runMain (module.js:492:10) | ||
at process.startup.processNextTick.process._tickCallback (node.js:244:9) | ||
You can also pass a `cause` argument, which is any other Error object: | ||
## Causes | ||
You can also pass a `cause` argument, which is another Error. For example: | ||
```javascript | ||
var fs = require('fs'); | ||
var VError = require('verror'); | ||
var filename = '/nonexistent'; | ||
fs.stat(filename, function (err1) { | ||
var err2 = new VError(err1, 'stat "%s" failed', filename); | ||
var err2 = new VError(err1, 'stat "%s"', filename); | ||
console.error(err2.message); | ||
@@ -64,3 +63,3 @@ }); | ||
stat "/nonexistent" failed: ENOENT, stat '/nonexistent' | ||
stat "/nonexistent": ENOENT, stat '/nonexistent' | ||
@@ -72,6 +71,8 @@ which resembles how Unix programs typically report errors: | ||
To match the Unixy feel, just prepend the program's name to the VError's | ||
`message`. | ||
To match the Unixy feel, when you print out the error, just prepend the | ||
program's name to the VError's `message`. Or just call | ||
[node-cmdutil.fail(your_verror)](https://github.com/joyent/node-cmdutil), which | ||
does this for you. | ||
You can also get the next-level Error using `err.cause()`: | ||
You can get the next-level Error using `err.cause()`: | ||
@@ -86,6 +87,6 @@ ```javascript | ||
Of course, you can nest these as many times as you want: | ||
Of course, you can chain these as many times as you want, and it works with any | ||
kind of Error: | ||
```javascript | ||
var VError = require('verror'); | ||
var err1 = new Error('No such file or directory'); | ||
@@ -102,43 +103,341 @@ var err2 = new VError(err1, 'failed to stat "%s"', '/junk'); | ||
The idea is that each layer in the stack annotates the error with a description | ||
of what it was doing (with a printf-like format string) and the result is a | ||
message that explains what happened at every level. | ||
of what it was doing. The end result is a message that explains what happened | ||
at each level. | ||
You can also decorate Error objects with additional information so that callers | ||
can not only handle each kind of error differently, but also construct their own | ||
error messages (e.g., to localize them, format them, group them by type, and so | ||
on). See the example below. | ||
## WError: wrap layered errors | ||
Sometimes you don't want an Error's "message" field to include the details of | ||
all of the low-level errors, but you still want to be able to get at them | ||
programmatically. For example, in an HTTP server, you probably don't want to | ||
spew all of the low-level errors back to the client, but you do want to include | ||
them in the audit log entry for the request. In that case, you can use a | ||
WError, which is created exactly like VError (and also supports both | ||
printf-style arguments and an optional cause), but the resulting "message" only | ||
contains the top-level error. It's also more verbose, including the class | ||
associated with each error in the cause chain. Using the same example above, | ||
but replacing `err3`'s VError with WError, so that it looks like this: | ||
# Deeper dive | ||
The two main goals for VError are: | ||
* **Make it easy to construct clear, complete error messages intended for | ||
people.** Clear error messages greatly improve both user experience and | ||
debuggability, so we wanted to make it easy to build them. That's why the | ||
constructor takes printf-style arguments. | ||
* **Make it easy to construct objects with programmatically-accessible | ||
metadata** (which we call _informational properties_). Instead of just saying | ||
"connection refused while connecting to 192.168.1.2:80", you can add | ||
properties like `"ip": "192.168.1.2"` and `"tcpPort": 80`. This can be used | ||
for feeding into monitoring systems, analyzing large numbers of Errors (as | ||
from a log file), or localizing error messages. | ||
To really make this useful, it also needs to be easy to compose Errors: | ||
higher-level code should be able to augment the Errors reported by lower-level | ||
code to provide a more complete description of what happened. Instead of saying | ||
"connection refused", you can say "operation X failed: connection refused". | ||
That's why VError supports `causes`. | ||
In order for all this to work, programmers need to know that it's generally safe | ||
to wrap lower-level Errors with higher-level ones. If you have existing code | ||
that handles Errors produced by a library, you should be able to wrap those | ||
Errors with a VError to add information without breaking the error handling | ||
code. There are two obvious ways that this could break such consumers: | ||
* The error's name might change. People typically use `name` to determine what | ||
kind of Error they've got. To ensure compatibility, you can create VErrors | ||
with custom names, but this approach isn't great because it prevents you from | ||
representing complex failures. For this reason, VError provides | ||
`findCauseByName`, which essentially asks: does this Error _or any of its | ||
causes_ have this specific type? If error handling code uses | ||
`findCauseByName`, then subsystems can construct very specific causal chains | ||
for debuggability and still let people handle simple cases easily. There's an | ||
example below. | ||
* The error's properties might change. People often hang additional properties | ||
off of Error objects. If we wrap an existing Error in a new Error, those | ||
properties would be lost unless we copied them. But there are a variety of | ||
both standard and non-standard Error properties that should _not_ be copied in | ||
this way: most obviously `name`, `message`, and `stack`, but also `fileName`, | ||
`lineNumber`, and a few others. Plus, it's useful for some Error subclasses | ||
to have their own private properties -- and there'd be no way to know whether | ||
these should be copied. For these reasons, VError first-classes these | ||
information properties. You have to provide them in the constructor, you can | ||
only fetch them with the `info()` function, and VError takes care of making | ||
sure properties from causes wind up in the `info()` output. | ||
Let's put this all together with an example from the node-fast RPC library. | ||
node-fast implements a simple RPC protocol for Node programs. There's a server | ||
and client interface, and clients make RPC requests to servers. Let's say the | ||
server fails with an UnauthorizedError with message "user 'bob' is not | ||
authorized". The client wraps all server errors with a FastServerError. The | ||
client also wraps all request errors with a FastRequestError that includes the | ||
name of the RPC call being made. The result of this failed RPC might look like | ||
this: | ||
name: FastRequestError | ||
message: "request failed: server error: user 'bob' is not authorized" | ||
rpcMsgid: <unique identifier for this request> | ||
rpcMethod: GetObject | ||
cause: | ||
name: FastServerError | ||
message: "server error: user 'bob' is not authorized" | ||
cause: | ||
name: UnauthorizedError | ||
message: "user 'bob' is not authorized" | ||
rpcUser: "bob" | ||
When the caller uses `VError.info()`, the information properties are collapsed | ||
so that it looks like this: | ||
message: "request failed: server error: user 'bob' is not authorized" | ||
rpcMsgid: <unique identifier for this request> | ||
rpcMethod: GetObject | ||
rpcUser: "bob" | ||
Taking this apart: | ||
* The error's message is a complete description of the problem. The caller can | ||
report this directly to its caller, which can potentially make its way back to | ||
an end user (if appropriate). It can also be logged. | ||
* The caller can tell that the request failed on the server, rather than as a | ||
result of a client problem (e.g., failure to serialize the request), a | ||
transport problem (e.g., failure to connect to the server), or something else | ||
(e.g., a timeout). They do this using `findCauseByName('FastServerError')` | ||
rather than checking the `name` field directly. | ||
* If the caller logs this error, the logs can be analyzed to aggregate | ||
errors by cause, by RPC method name, by user, or whatever. Or the | ||
error can be correlated with other events for the same rpcMsgid. | ||
* It wasn't very hard for any part of the code to contribute to this Error. | ||
Each part of the stack has just a few lines to provide exactly what it knows, | ||
with very little boilerplate. | ||
It's not expected that you'd use these complex forms all the time. Despite | ||
supporting the complex case above, you can still just do: | ||
new VError("my service isn't working"); | ||
for the simple cases. | ||
# Reference: VError, WError, SError | ||
VError, WError, and SError are convenient drop-in replacements for `Error` that | ||
support printf-style arguments, first-class causes, informational properties, | ||
and other useful features. | ||
## Constructors | ||
The VError constructor has several forms: | ||
```javascript | ||
var verror = require('verror'); | ||
var err1 = new Error('No such file or directory'); | ||
var err2 = new verror.VError(err1, 'failed to stat "%s"', '/junk'); | ||
var err3 = new verror.WError(err2, 'request failed'); | ||
console.error(err3.message); | ||
/* | ||
* This is the most general form. You can specify any supported options | ||
* (including "cause" and "info") this way. | ||
*/ | ||
new VError(options, sprintf_args...) | ||
/* | ||
* This is a useful shorthand when the only option you need is "cause". | ||
*/ | ||
new VError(cause, sprintf_args...) | ||
/* | ||
* This is a useful shorthand when you don't need any options at all. | ||
*/ | ||
new VError(sprintf_args...) | ||
``` | ||
we get this output: | ||
All of these forms construct a new VError that behaves just like the built-in | ||
JavaScript `Error` class, with some additional methods described below. | ||
request failed | ||
In the first form, `options` is a plain object with any of the following | ||
optional properties: | ||
That's what we wanted -- just a high-level summary for the client. But we can | ||
get the object's toString() for the full details: | ||
Option name | Type | Meaning | ||
---------------- | ---------------- | ------- | ||
`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. | ||
`cause` | any Error object | Indicates that the new error was caused by `cause`. See `cause()` below. If unspecified, the cause will be `null`. | ||
`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. | ||
`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. | ||
`info` | object | Specifies arbitrary informational properties that are available through the `VError.info(err)` static class method. See that method for details. | ||
WError: request failed; caused by WError: failed to stat "/nonexistent"; | ||
caused by Error: No such file or directory | ||
The second form is equivalent to using the first form with the specified `cause` | ||
as the error's cause. This form is distinguished from the first form because | ||
the first argument is an Error. | ||
For a complete example, see examples/werror.js. | ||
The third form is equivalent to using the first form with all default option | ||
values. This form is distinguished from the other forms because the first | ||
argument is not an object or an Error. | ||
The `WError` constructor is used exactly the same way as the `VError` | ||
constructor. The `SError` constructor is also used the same way as the | ||
`VError` constructor except that in all cases, the `strict` property is | ||
overriden to `true. | ||
## Public properties | ||
`VError`, `WError`, and `SError` all provide the same public properties as | ||
JavaScript's built-in Error objects. | ||
Property name | Type | Meaning | ||
------------- | ------ | ------- | ||
`name` | string | Programmatically-usable name of the error. | ||
`message` | string | Human-readable summary of the failure. Programmatically-accessible details are provided through `VError.info(err)` class method. | ||
`stack` | string | Human-readable stack trace where the Error was constructed. | ||
For all of these classes, the printf-style arguments passed to the constructor | ||
are processed with `sprintf()` to form a message. For `WError`, this becomes | ||
the complete `message` property. For `SError` and `VError`, this message is | ||
prepended to the message of the cause, if any (with a suitable separator), and | ||
the result becomes the `message` property. | ||
The `stack` property is managed entirely by the underlying JavaScript | ||
implementation. It's generally implemented using a getter function because | ||
constructing the human-readable stack trace is somewhat expensive. | ||
## Class methods | ||
The following methods are defined on the `VError` class and as exported | ||
functions on the `verror` module. They're defined this way rather than using | ||
methods on VError instances so that they can be used on Errors not created with | ||
`VError`. | ||
### `VError.cause(err)` | ||
The `cause()` function returns the next Error in the cause chain for `err`, or | ||
`null` if there is no next error. See the `cause` argument to the constructor. | ||
Errors can have arbitrarily long cause chains. You can walk the `cause` chain | ||
by invoking `VError.cause(err)` on each subsequent return value. If `err` is | ||
not a `VError`, the cause is `null`. | ||
### `VError.info(err)` | ||
Returns an object with all of the extra error information that's been associated | ||
with this Error and all of its causes. These are the properties passed in using | ||
the `info` option to the constructor. Properties not specified in the | ||
constructor for this Error are implicitly inherited from this error's cause. | ||
These properties are intended to provide programmatically-accessible metadata | ||
about the error. For an error that indicates a failure to resolve a DNS name, | ||
informational properties might include the DNS name to be resolved, or even the | ||
list of resolvers used to resolve it. The values of these properties should | ||
generally be plain objects (i.e., consisting only of null, undefined, numbers, | ||
booleans, strings, and objects and arrays containing only other plain objects). | ||
## Examples | ||
The "Demo" section above covers several basic cases. Here's a more advanced | ||
case: | ||
```javascript | ||
var err1 = new VError('something bad happened'); | ||
/* ... */ | ||
var err2 = new VError({ | ||
'name': 'ConnectionError', | ||
'cause': err1, | ||
'info': { | ||
'errno': 'ECONNREFUSED', | ||
'remote_ip': '127.0.0.1', | ||
'port': 215 | ||
} | ||
}, 'failed to connect to "%s:%d"', '127.0.0.1', 215); | ||
console.log(err2.message); | ||
console.log(err2.name); | ||
console.log(VError.info(err2)); | ||
console.log(err2.stack); | ||
``` | ||
This outputs: | ||
failed to connect to "127.0.0.1:215": something bad happened | ||
ConnectionError | ||
{ errno: 'ECONNREFUSED', remote_ip: '127.0.0.1', port: 215 } | ||
ConnectionError: failed to connect to "127.0.0.1:215": something bad happened | ||
at Object.<anonymous> (/home/dap/node-verror/examples/info.js:5:12) | ||
at Module._compile (module.js:456:26) | ||
at Object.Module._extensions..js (module.js:474:10) | ||
at Module.load (module.js:356:32) | ||
at Function.Module._load (module.js:312:12) | ||
at Function.Module.runMain (module.js:497:10) | ||
at startup (node.js:119:16) | ||
at node.js:935:3 | ||
Information properties are inherited up the cause chain, with values at the top | ||
of the chain overriding same-named values lower in the chain. To continue that | ||
example: | ||
```javascript | ||
var err3 = new VError({ | ||
'name': 'RequestError', | ||
'cause': err2, | ||
'info': { | ||
'errno': 'EBADREQUEST' | ||
} | ||
}, 'request failed'); | ||
console.log(err3.message); | ||
console.log(err3.name); | ||
console.log(VError.info(err3)); | ||
console.log(err3.stack); | ||
``` | ||
This outputs: | ||
request failed: failed to connect to "127.0.0.1:215": something bad happened | ||
RequestError | ||
{ errno: 'EBADREQUEST', remote_ip: '127.0.0.1', port: 215 } | ||
RequestError: request failed: failed to connect to "127.0.0.1:215": something bad happened | ||
at Object.<anonymous> (/home/dap/node-verror/examples/info.js:20:12) | ||
at Module._compile (module.js:456:26) | ||
at Object.Module._extensions..js (module.js:474:10) | ||
at Module.load (module.js:356:32) | ||
at Function.Module._load (module.js:312:12) | ||
at Function.Module.runMain (module.js:497:10) | ||
at startup (node.js:119:16) | ||
at node.js:935:3 | ||
# Reference: MultiError | ||
MultiError is an Error class that represents a group of Errors. This is used | ||
when you logically need to provide a single Error, but you want to preserve | ||
information about multiple underying Errors. A common case is when you execute | ||
several operations in parallel and some of them fail. | ||
MultiErrors are constructed as: | ||
```javascript | ||
new MultiError(error_list) | ||
``` | ||
`error_list` is an array of at least one `Error` object. | ||
The cause of the MultiError is the first error provided. None of the other | ||
`VError` options are supported. The `message` for a MultiError consists the | ||
`message` from the first error, prepended with a message indicating that there | ||
were other errors. | ||
For example: | ||
```javascript | ||
err = new MultiError([ | ||
new Error('failed to resolve DNS name "abc.example.com"'), | ||
new Error('failed to resolve DNS name "def.example.com"'), | ||
]); | ||
console.error(err.message); | ||
``` | ||
outputs: | ||
first of 2 errors: failed to resolve DNS name "abc.example.com" | ||
## Public methods | ||
### `errors()` | ||
Returns an array of the errors used to construct this MultiError. | ||
# Contributing | ||
Contributions welcome. Code should be "make check" clean. To run "make check", | ||
you'll need these tools: | ||
Contributions should be "make prepush" clean. To run "make check", you'll need | ||
these tools: | ||
@@ -145,0 +444,0 @@ * https://github.com/davepacheco/jsstyle |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Debug access
Supply chain riskUses debug, reflection and dynamic code execution features.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
444
0
30666
3
6
350
1
+ Addedassert-plus@^1.0.0
+ Addedassert-plus@1.0.0(transitive)
+ Addedextsprintf@1.4.1(transitive)
- Removedextsprintf@1.2.0(transitive)
Updatedextsprintf@^1.2.0