Node.js – process.emitWarning() 方法


process.emitWarning() 方法可用於傳送自定義或使用者定義的程序警告。可以透過向 warning 事件新增處理程式來收聽此通知。

語法

process.emitWarning(warning, [options])

引數

  • warning – 即將傳送的警告。

  • options

    • type – 這是發出警告的型別。預設“Warning”

    • code – 這是將傳送的警告的唯一識別符號。

    • ctor – 這是用於限制產生的堆疊跟蹤的可選功能。

    • detail – 這是要包含在錯誤中的附加文字。

示例 1

建立一個名為 "warning.js" 的檔案,然後複製以下程式碼片段。建立該檔案後,使用命令 "node warning.js" 執行此程式碼。

console.log("Start ...");

// Interval set to keep the process running
setInterval(() => {
console.log("Running ...");}, 1000);

setTimeout(() => {
   process.emitWarning('An Error occured!', {
      code: 'Custom_Warning',
      detail: 'Additional information about warning'
   });
}, 4000);

// Start listening
process.on('warning', (warning) => {

   // Print msg if there is a warning
   if (warning) {
      console.log(warning);
      process.exit(0);
   }
});

輸出

Start ...
Running ...
Running ...
Running ...
{ [object Object]: An Error occured!
at Timeout.setTimeout (/home/cg/root/8008764/main.js:8:12)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
name:
{ code: 'Custom_Warning',
detail: 'Additional information about warning' } }
(node:13011) [object Object]: An Error occured!

示例 2

我們來看一下另一個示例。

console.log("Start ...");

// Interval set to keep the process running
setInterval(() => {
   console.log("Running ...");
}, 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);

// Start listening
process.on('warning', (warning) => {

   // Print msg if there is an Important warning
   if (warning.name === 'IMPORTANT') {
      console.log('Fix this ASAP!')
      process.exit(0);
   }
});

輸出

Start ...
Running ...
Running ...
Running ...
Running ...
Running ...
Running ...
Running ...
Running ...
Running ...
(node:18756) [object Object]: An Error occured!
(node:18756) [object Object]: ALERT! WARNING OCCURED

更新於:29-Oct-2021

182 次觀看

開始您的 職業

透過完成課程來獲得認證

立即開始
廣告
© . All rights reserved.