📜  Node.js 处理 uncaughtException 事件

📅  最后修改于: 2022-05-13 01:56:19.811000             🧑  作者: Mango

Node.js 处理 uncaughtException 事件

'uncaughtException'是 process 模块中的 Process 类的事件,当未捕获的 JavaScript 异常一直冒泡返回事件循环时会发出该事件。

句法:

Event: 'uncaughtException'

参数:此事件不接受任何参数作为参数。

返回值:此事件只返回一个回调函数以供进一步操作。

示例 1:

index.js
// Node.js program to demonstrate the  
// Process 'uncaughtException' Event
  
// Importing the modules
const process = require('process');
var fs = require('fs');
  
// Independent Block which will execute
setTimeout(() => {
   console.log('\n')
   console.log('Greetings from GeeksforGeeks');
}, 1000);
  
// Event 'uncaughtException'
process.on('uncaughtException', (error, source) => {
   fs.writeSync(process.stderr.fd, error, source);
});
  
// Throwing an exception
nonexistentFunc();
  
console.log('This Block of code will not run');


index.js
// Node.js program to demonstrate the  
// Process 'uncaughtException' Event
  
// Importing the modules
const process = require('process');
var fs = require('fs');
  
// Event 'uncaughtException'
process.on('uncaughtException', (error) => {
   fs.writeSync(process.stderr.fd, error);
});
  
// Throwing our Error
throw new Error('Ran out of coffee')


使用以下命令运行index.js文件:

node index.js

输出:

ReferenceError: nonexistentFunc is not defined

Greetings from GeeksforGeeks

示例 2:

index.js

// Node.js program to demonstrate the  
// Process 'uncaughtException' Event
  
// Importing the modules
const process = require('process');
var fs = require('fs');
  
// Event 'uncaughtException'
process.on('uncaughtException', (error) => {
   fs.writeSync(process.stderr.fd, error);
});
  
// Throwing our Error
throw new Error('Ran out of coffee')

使用以下命令运行index.js文件:

node index.js

输出:

Error: Ran out of coffee

参考: https://nodejs.org/dist/latest-v16.x/docs/api/process.html#process_event_uncaughtexception