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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP