跳到主要内容

认识

2024年05月11日
柏拉文
越努力,越幸运

一、try/catch


一般情况下,我们会将有可能出错的代码放到 try/catch 块里。但是到了 Node.js,由于 try/catch 无法捕捉异步回调里的异常

语法

try {
// 尝试执行的代码
const result = synchronousFunctionThatMightFail();
console.log(result);
} catch (error) {
// 发生异常时执行的代码
console.error('An error occurred:', error.message);
}

二、domain.on('error') [已弃用]


Node.js 中,domain 模块用于处理异步操作中的错误和异常,该模块允许开发人员将相关的 I/O 操作分组并在发生错误时捕获异常,从而避免应用程序崩溃。

不过,自 Node.js 版本 15.0.0 开始,domain 模块已经被宣布为废弃模块,并且不再被官方推荐使用。这是因为 domain 模块有一些设计缺陷,例如可能会导致资源泄漏,同时也不符合异步编程的最佳实践。

语法

const domainNew = domain.create();

domainNew.on('error', function(err) {
console.error('Error caught by domain:', err);
});

domainNew.run(function() {
function test() {
throw new Error("test");
}

test();
});

三、process.on('uncaughtException')


当系统发生异常,且没有被 try…catch 捕获时,会触发 uncaughtException 事件。该方法适用于全局的异常捕获,来避免 Node.js 进程的崩溃,但该方法仅仅用于异常捕获,无法做成相应的异常处理,因为无法定位到发生异常的上下文。而且一旦 uncaughtException 事件触发,整个 node 进程将 crash 掉,如果不做一些善后处理的话会导致整个服务挂掉,这对于线上的服务来说将是非常不好的。

语法

process.on("uncaughtException", function (err) {
console.error("Uncaught Exception:", err.message, err.stack);
process.exit(1);
});

function test() {
throw new Error("test");
}

test();

四、process.on('unhandledRejection')


用于监听Promise的未处理拒绝。当Promise被拒绝且拒绝未被处理时,该事件被触发。

语法

process.on('unhandledRejection', function (reason, promise) {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
process.exit(1);
})

function test() {
throw new Error('test');
}

test();