Node.js – process.emitWarning() 方法
该方法可用于发出自定义或用户定义的进程警告。这可以通过向警告事件添加处理程序来侦听。process.emitWarning()
语法
process.emitWarning(warning, [options])
参数
警告-这是将发出的警告。
选项——
type-这是发出的警告类型。默认“警告”
代码-这是将发出的警告的唯一标识符。
ctor-这是一个可选函数,用于限制生成的堆栈跟踪。
详细信息-这是要包含在错误中的附加文本。
示例1
创建一个名为“warning.js”的文件并复制以下代码片段。创建文件后,使用命令“nodewarning.js”运行此代码。
console.log("开始..."); //设置间隔以保持进程运行 setInterval(() => { console.log("跑步...");}, 1000); setTimeout(() => { process.emitWarning('An Error occured!', { code: 'Custom_Warning', detail: 'Additional information about warning' }); }, 4000); //开始聆听 process.on('warning', (warning) => { //如果有警告,则打印msg if (warning) { console.log(warning); process.exit(0); } });输出结果
开始... 跑步... 跑步... 跑步... { [object Object]: An Error occured! atTimeout.setTimeout(/home/cg/root/8008764/main.js:8:12) at ontimeout (timers.js:386:14) at tryOnTimeout (timers.js:250:5) atTimer.listOnTimeout(timers.js:214:5) name: { code: 'Custom_Warning', detail: 'Additional information about warning' } } (node:13011) [object Object]: An Error occured!
示例2
让我们再看一个例子。
console.log("开始..."); //设置间隔以保持进程运行 setInterval(() => { console.log("跑步..."); }, 1000); setTimeout(() => { process.emitWarning('An Error occured!', { code: 'Custom_Warning', detail: 'Additional information about warning' }); }, 2000); setTimeout(() => { process.emitWarning('ALERT! WARNING OCCURED', { type: 'IMPORTANT', code: '001', detail: 'Can not proceed further!' }); }, 4000); //开始聆听 process.on('warning', (warning) => { //如果有重要警告,则打印msg if (warning.name === 'IMPORTANT') { console.log('Fix this ASAP!') process.exit(0); } });输出结果
开始... 跑步... 跑步... 跑步... 跑步... 跑步... 跑步... 跑步... 跑步... 跑步... (node:18756) [object Object]: An Error occured! (node:18756) [object Object]: ALERT! WARNING OCCURED