Node.js中出现未捕获异常的处理方法
- 作者: 亖呉?盀
- 来源: 51数据库
- 2021-08-05
前言
node.js 程序运行在单进程上,应用开发时一个难免遇到的问题就是异常处理,对于一些未捕获的异常处理起来,也不是一件容易的事情。
未捕获异常的程序
下面展示了一段简单的应用程序,如下所示:
const http = require('http');
const port = 3000;
const server = http.createserver((req, res) => {
if (req.url === '/error') {
a.b;
res.end('error');
} else {
settimeout(() => res.end('ok!'), 1000 * 10);
}
});
server.listen(port, () => console.log(`port is listening on ${port}.`));
运行以上程序,在右侧第二个窗口中执行了 /error 路由,因为没有定义 a 这个对象,则会引发错误。

进程崩溃退出之后导致整个应用程序也将崩溃,左侧是一个延迟的响应,也将无法正常工作。
这是一个头疼的问题,不要紧,下文我们将会学到一个优雅退出的方案。
进程崩溃优雅退出
关于错误捕获,node.js 官网曾提供了一个模块 domain 来实现,但是现在已废弃了所以就不再考虑了。
之前在看 cnpm 这个项目时看到了以下关于错误退出的一段代码:
// http://www.51sjk.com/Upload/Articles/1/0/262/262239_20210702002439789.js#l18
graceful({
server: [registry, web],
error: function (err, throwerrorcount) {
if (err.message) {
err.message += ' (uncaughtexception throw ' + throwerrorcount + ' times on pid:' + process.pid + ')';
}
console.error(err);
console.error(err.stack);
logger.error(err);
}
});
上述使用的是 graceful 这个模块,在 npm 上可以找到。
实现一个 graceful.js
实现一个 graceful 函数,初始化加载时注册 uncaughtexception、unhandledrejection 两个错误事件,分别监听未捕获的错误信息和未捕获的 promise 错误信息。
const http = require('http');
/**
* graceful
* @param { number } options.killtimeout 超时时间
* @param { function } options.onerror 产生错误信息会执行该回调函数
* @param { array } options.servers http server
* @returns
*/
function graceful(options = {}) {
options.killtimeout = options.killtimeout || 1000 * 30;
options.onerror = options.onerror || function () {};
options.servers= options.servers || [];
process.on('uncaughtexception', error => handleuncaughtexception(error, options));
process.on('unhandledrejection', error => handleunhandledrejection(error, options));
}
handleuncaughtexception、handleunhandledrejection 分别接收相应的错误事件,执行应用传入的 onerror() 将错误信息进行回传,最后调用 handleerror()。
const throwcount = {
uncaughtexception: 0,
unhandledrejection: 0
};
function handleuncaughtexception(error, options) {
throwcount.uncaughtexception += 1;
options.onerror(error, 'uncaughtexception', throwcount.uncaughtexception);
if (throwcount.uncaughtexception > 1) return;
handleerror(options);
};
function handleunhandledrejection(error, options) {
throwcount.unhandledrejection += 1;
options.onerror(error, 'unhandledrejection', throwcount.unhandledrejection);
if (throwcount.unhandledrejection > 1) return;
handleerror(options);
}
handleerror 方法为核心实现,首先遍历应用传入的 servers,监听 request 事件,在未捕获错误触发之后,如果还有请求链接,则关闭当前请求的链接。
之后,执行 settimeout 延迟退出,也就是最大可能的等待之前链接处理完成。
function handleerror(options) {
const { servers, killtimeout } = options;
// 关闭当前请求的链接
for (const server of servers) {
console.log('server instanceof http.server: ', server instanceof http.server);
if (server instanceof http.server) {
server.on('request', (req, res) => {
req.shouldkeepalive = false;
res.shouldkeepalive = false;
if (!res._header) {
res.setheader('connection', 'close');
}
});
}
}
// 延迟退出
const timer = settimeout(() => {
process.exit(1);
}, killtimeout);
if (timer && timer.unref) {
timer.unref();
}
}
module.exports = graceful;
应用程序中使用上述实现
加载上述 graceful.js 使用起来很简单只需要在文件尾部,加载 graceful 函数并传入相应参数即可。
const graceful = require('./graceful.js');
...
server.listen(port, () => console.log(`port is listening on ${port}.`));
graceful({
servers: [server],
onerror: (error, type, throwerrorcount) => {
console.log('[%s] [pid: %s] [throwerrorcount: %s] %s: %s', new date(), process.pid, throwerrorcount, type, error.stack || error);
}
});
再次运行应用程序,看看效果:

这一次,即使右侧 /error 路由产生未捕获异常,也将不会引起左侧请求无法正常响应。
graceful 模块
最后推荐一个 npm 模块 graceful,引用文档中的一句话:“it's the best way to handle uncaughtexception on current situations.”
该模块还提供了对于 node.js 中 cluster 模块的支持。
安装
$ npm install graceful -s
应用
如果一个进程中有多个 server,将它们添加到 servers 中即可。
const graceful = require('graceful');
...
graceful({
servers: [server1, server2, restapi],
killtimeout: '15s',
});
总结
如果你正在使用 node.js 对于异常你需要有些了解,上述讲解的两个异常事件可以做为你的最后补救措施,但是不应该当作 on error resume next(出了错误就恢复让它继续)的等价机制。
到此这篇关于node.js中出现未捕获异常处理方法的文章就介绍到这了,更多相关node.js未捕获异常内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
reference
- nodejs.cn/api/process.html
- www.npmjs.com/package/graceful
