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
广告