process: add optional detail to process emitWarning

Adds a new method signature variant for process.emitWarning()
that accepts an options object. The options object may include
a new `detail` option that allows additional detail text to be
associated with the warning. By default, this additional text
will be printed to stderr along with the warning, and included
on the Warning Error object using the `.detail` property.

e.g.

```js
process.emitWarning('A message', {
  code: 'WARNING123',
  detail: 'This is additional detail'
});
// Emits:
// (node {pid}) [WARNING123] Warning: A message
// This is additional detail
```

PR-URL: https://github.com/nodejs/node/pull/12725
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
This commit is contained in:
James M Snell 2017-04-28 09:06:10 -07:00
parent 23fc082409
commit dd20e68b0f
3 changed files with 106 additions and 35 deletions

View File

@ -637,6 +637,52 @@ process's [`ChildProcess.disconnect()`][].
If the Node.js process was not spawned with an IPC channel, If the Node.js process was not spawned with an IPC channel,
`process.disconnect()` will be `undefined`. `process.disconnect()` will be `undefined`.
## process.emitWarning(warning[, options])
<!-- YAML
added: REPLACEME
-->
* `warning` {string|Error} The warning to emit.
* `options` {Object}
* `type` {string} When `warning` is a String, `type` is the name to use
for the *type* of warning being emitted. Default: `Warning`.
* `code` {string} A unique identifier for the warning instance being emitted.
* `ctor` {Function} When `warning` is a String, `ctor` is an optional
function used to limit the generated stack trace. Default
`process.emitWarning`
* `detail` {string} Additional text to include with the error.
The `process.emitWarning()` method can be used to emit custom or application
specific process warnings. These can be listened for by adding a handler to the
[`process.on('warning')`][process_warning] event.
```js
// Emit a warning with a code and additional detail.
process.emitWarning('Something happened!', {
code: 'MY_WARNING',
detail: 'This is some additional information'
});
// Emits:
// (node:56338) [MY_WARNING] Warning: Something happened!
// This is some additional information
```
In this example, an `Error` object is generated internally by
`process.emitWarning()` and passed through to the
[`process.on('warning')`][process_warning] event.
```js
process.on('warning', (warning) => {
console.warn(warning.name); // 'Warning'
console.warn(warning.message); // 'Something happened!'
console.warn(warning.code); // 'MY_WARNING'
console.warn(warning.stack); // Stack trace
console.warn(warning.detail); // 'This is some additional information'
});
```
If `warning` is passed as an `Error` object, the `options` argument is ignored.
## process.emitWarning(warning[, type[, code]][, ctor]) ## process.emitWarning(warning[, type[, code]][, ctor])
<!-- YAML <!-- YAML
added: v6.0.0 added: v6.0.0
@ -655,13 +701,13 @@ specific process warnings. These can be listened for by adding a handler to the
[`process.on('warning')`][process_warning] event. [`process.on('warning')`][process_warning] event.
```js ```js
// Emit a warning using a string... // Emit a warning using a string.
process.emitWarning('Something happened!'); process.emitWarning('Something happened!');
// Emits: (node: 56338) Warning: Something happened! // Emits: (node: 56338) Warning: Something happened!
``` ```
```js ```js
// Emit a warning using a string and a type... // Emit a warning using a string and a type.
process.emitWarning('Something Happened!', 'CustomWarning'); process.emitWarning('Something Happened!', 'CustomWarning');
// Emits: (node:56338) CustomWarning: Something Happened! // Emits: (node:56338) CustomWarning: Something Happened!
``` ```
@ -689,14 +735,14 @@ If `warning` is passed as an `Error` object, it will be passed through to the
`code` and `ctor` arguments will be ignored): `code` and `ctor` arguments will be ignored):
```js ```js
// Emit a warning using an Error object... // Emit a warning using an Error object.
const myWarning = new Error('Warning! Something happened!'); const myWarning = new Error('Something happened!');
// Use the Error name property to specify the type name // Use the Error name property to specify the type name
myWarning.name = 'CustomWarning'; myWarning.name = 'CustomWarning';
myWarning.code = 'WARN001'; myWarning.code = 'WARN001';
process.emitWarning(myWarning); process.emitWarning(myWarning);
// Emits: (node:56338) [WARN001] CustomWarning: Warning! Something happened! // Emits: (node:56338) [WARN001] CustomWarning: Something happened!
``` ```
A `TypeError` is thrown if `warning` is anything other than a string or `Error` A `TypeError` is thrown if `warning` is anything other than a string or `Error`

View File

@ -90,30 +90,37 @@ function setupProcessWarnings() {
if (isDeprecation && process.noDeprecation) return; if (isDeprecation && process.noDeprecation) return;
const trace = process.traceProcessWarnings || const trace = process.traceProcessWarnings ||
(isDeprecation && process.traceDeprecation); (isDeprecation && process.traceDeprecation);
let msg = `${prefix}`;
if (warning.code)
msg += `[${warning.code}] `;
if (trace && warning.stack) { if (trace && warning.stack) {
if (warning.code) { msg += `${warning.stack}`;
output(`${prefix}[${warning.code}] ${warning.stack}`);
} else {
output(`${prefix}${warning.stack}`);
}
} else { } else {
const toString = const toString =
typeof warning.toString === 'function' ? typeof warning.toString === 'function' ?
warning.toString : Error.prototype.toString; warning.toString : Error.prototype.toString;
if (warning.code) { msg += `${toString.apply(warning)}`;
output(`${prefix}[${warning.code}] ${toString.apply(warning)}`);
} else {
output(`${prefix}${toString.apply(warning)}`);
}
} }
if (typeof warning.detail === 'string') {
msg += `\n${warning.detail}`;
}
output(msg);
}); });
} }
// process.emitWarning(error) // process.emitWarning(error)
// process.emitWarning(str[, type[, code]][, ctor]) // process.emitWarning(str[, type[, code]][, ctor])
// process.emitWarning(str[, options])
process.emitWarning = function(warning, type, code, ctor) { process.emitWarning = function(warning, type, code, ctor) {
const errors = lazyErrors(); const errors = lazyErrors();
if (typeof type === 'function') { var detail;
if (type !== null && typeof type === 'object' && !Array.isArray(type)) {
ctor = type.ctor;
code = type.code;
if (typeof type.detail === 'string')
detail = type.detail;
type = type.type || 'Warning';
} else if (typeof type === 'function') {
ctor = type; ctor = type;
code = undefined; code = undefined;
type = 'Warning'; type = 'Warning';
@ -130,6 +137,7 @@ function setupProcessWarnings() {
warning = new Error(warning); warning = new Error(warning);
warning.name = String(type || 'Warning'); warning.name = String(type || 'Warning');
if (code !== undefined) warning.code = code; if (code !== undefined) warning.code = code;
if (detail !== undefined) warning.detail = detail;
Error.captureStackTrace(warning, ctor || process.emitWarning); Error.captureStackTrace(warning, ctor || process.emitWarning);
} }
if (!(warning instanceof Error)) { if (!(warning instanceof Error)) {

View File

@ -4,30 +4,48 @@
const common = require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const util = require('util');
const testMsg = 'A Warning';
const testCode = 'CODE001';
const testDetail = 'Some detail';
const testType = 'CustomWarning';
process.on('warning', common.mustCall((warning) => { process.on('warning', common.mustCall((warning) => {
assert(warning); assert(warning);
assert(/^(Warning|CustomWarning)/.test(warning.name)); assert(/^(Warning|CustomWarning)/.test(warning.name));
assert.strictEqual(warning.message, 'A Warning'); assert.strictEqual(warning.message, testMsg);
if (warning.code) assert.strictEqual(warning.code, 'CODE001'); if (warning.code) assert.strictEqual(warning.code, testCode);
}, 8)); if (warning.detail) assert.strictEqual(warning.detail, testDetail);
}, 15));
process.emitWarning('A Warning'); class CustomWarning extends Error {
process.emitWarning('A Warning', 'CustomWarning'); constructor() {
process.emitWarning('A Warning', CustomWarning); super();
process.emitWarning('A Warning', 'CustomWarning', CustomWarning); this.name = testType;
process.emitWarning('A Warning', 'CustomWarning', 'CODE001'); this.message = testMsg;
this.code = testCode;
function CustomWarning() { Error.captureStackTrace(this, CustomWarning);
Error.call(this); }
this.name = 'CustomWarning';
this.message = 'A Warning';
this.code = 'CODE001';
Error.captureStackTrace(this, CustomWarning);
} }
util.inherits(CustomWarning, Error);
process.emitWarning(new CustomWarning()); [
[testMsg],
[testMsg, testType],
[testMsg, CustomWarning],
[testMsg, testType, CustomWarning],
[testMsg, testType, testCode],
[testMsg, { type: testType }],
[testMsg, { type: testType, code: testCode }],
[testMsg, { type: testType, code: testCode, detail: testDetail }],
[new CustomWarning()],
// detail will be ignored for the following. No errors thrown
[testMsg, { type: testType, code: testCode, detail: true }],
[testMsg, { type: testType, code: testCode, detail: [] }],
[testMsg, { type: testType, code: testCode, detail: null }],
[testMsg, { type: testType, code: testCode, detail: 1 }]
].forEach((i) => {
assert.doesNotThrow(() => process.emitWarning.apply(null, i));
});
const warningNoToString = new CustomWarning(); const warningNoToString = new CustomWarning();
warningNoToString.toString = null; warningNoToString.toString = null;
@ -47,7 +65,6 @@ assert.throws(() => process.emitWarning(1), expectedError);
assert.throws(() => process.emitWarning({}), expectedError); assert.throws(() => process.emitWarning({}), expectedError);
assert.throws(() => process.emitWarning(true), expectedError); assert.throws(() => process.emitWarning(true), expectedError);
assert.throws(() => process.emitWarning([]), expectedError); assert.throws(() => process.emitWarning([]), expectedError);
assert.throws(() => process.emitWarning('', {}), expectedError);
assert.throws(() => process.emitWarning('', '', {}), expectedError); assert.throws(() => process.emitWarning('', '', {}), expectedError);
assert.throws(() => process.emitWarning('', 1), expectedError); assert.throws(() => process.emitWarning('', 1), expectedError);
assert.throws(() => process.emitWarning('', '', 1), expectedError); assert.throws(() => process.emitWarning('', '', 1), expectedError);