emitWarning
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 'warning'
event.
import { emitWarning } from 'node:process';
// Emit a warning using a string.
emitWarning('Something happened!');
// Emits: (node: 56338) Warning: Something happened!
import { emitWarning } from 'node:process';
// Emit a warning using a string and a type.
emitWarning('Something Happened!', 'CustomWarning');
// Emits: (node:56338) CustomWarning: Something Happened!
import { emitWarning } from 'node:process';
emitWarning('Something happened!', 'CustomWarning', 'WARN001');
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
```js
In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the `'warning'` handler.
```js
import process from 'node:process';
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, it will be passed through to the 'warning'
event handler unmodified (and the optional type
, code
and ctor
arguments will be ignored):
import { emitWarning } from 'node:process';
// Emit a warning using an Error object.
const myWarning = new Error('Something happened!');
// Use the Error name property to specify the type name
myWarning.name = 'CustomWarning';
myWarning.code = 'WARN001';
emitWarning(myWarning);
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
A TypeError
is thrown if warning
is anything other than a string or Error
object.
While process warnings use Error
objects, the process warning mechanism is not a replacement for normal error handling mechanisms.
The following additional handling is implemented if the warning type
is 'DeprecationWarning'
:
If the
--throw-deprecation
command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event.If the
--no-deprecation
command-line flag is used, the deprecation warning is suppressed.If the
--trace-deprecation
command-line flag is used, the deprecation warning is printed tostderr
along with the full stack trace.
Since
v8.0.0
Parameters
The warning to emit.