阅读 350

Node.js – process.emitWarning() 方法

该方法可用于发出自定义或用户定义的进程警告。这可以通过向警告事件添加处理程序来侦听。process.emitWarning()

语法


process.emitWarning(warning, [options])


参数

  • 警告- 这是将发出的警告。

  • 选项——

    • type - 这是发出的警告类型。默认“警告”

    • 代码- 这是将发出的警告的唯一标识符。

    • ctor - 这是一个可选函数,用于限制生成的堆栈跟踪。

    • 详细信息- 这是要包含在错误中的附加文本。

示例 1

创建一个名为“warning.js”的文件并复制以下代码片段。创建文件后,使用命令“node warning.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


文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐