Node.js Process uncaughtException事件

Node.js Process uncaughtException事件

‘uncaughtException’是处理模块内部的进程类的事件,当一个未捕获的JavaScript异常通过事件循环返回时,它会被触发。

语法:

Event: 'uncaughtException'

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

返回值: 此事件只返回一个用于进一步操作的回调函数。

示例1:

// 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 index.js

输出:

ReferenceError: nonexistentFunc is not defined

Greetings from GeeksforGeeks

示例2:

// Node.js program to demonstrate the
// Process 'uncaughtException' Event
 
// Importing the modules
const process = require('process');
const 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程