可以使用 process.on('uncaughtException')
或 process.on('unhandledRejection')
来捕获全局的错误。例如:
process.on('uncaughtException', function(err) {
console.error('There was an uncaught error', err);
process.exit(1); // mandatory (as per the Node.js docs)
});
或
process.on('unhandledRejection', function(reason, p) {
console.error('There was an unhandled rejection', p, 'reason:', reason);
process.exit(1); // mandatory (as per the Node.js docs)
});
这两个事件处理器在 Node.js 中是全局的,因此可以在任何地方使用它们捕获错误。
注意:这种方法仅应用于未在 try/catch 语句块中捕获的错误。对于在 try/catch 语句块中捕获的错误,可以使用 try/catch 语句来处理。