cluster和domain结合让express异常处理更加简单
发布于 7 年前 作者 839305939wang 2812 次浏览 来自 分享

目前nodejs常规的异常处理有三种

  1. try catch
  2. uncaughtException
  3. domain 我将cluster和domain进行了结合,用于处理express框架搭建的web应用的异常处理 使用方法:
	let express = require("express");
let app = express();
let ecd = require("express-cluster-domain");
app.use(ecd.clusterDomain({
	killTimeout:1000,
  error:function(err){
     console.log("sorry!request bad!");
  }
}));
app.get("/",(req,res)=>{
	 setTimeout(function(){
		if(Math.random()>0.5){
			throw new Error("Error from timeout");
		}else{
			console.log("訪問正常");
			res.send("request success!")
		}
	 },2000)
});
ecd.startServer(function(){
	app.listen(8080);
})

模块github地址https://github.com/839305939wang/express-cluster-domain.git

7 回复

domain 还是算了… 马上要废弃的 API 了

@atian25 那现在用什么处理异常呢?domain起码比前面两种靠谱吧?虽然有的异常他也捕获不了

常规异常控制+process.on(‘uncaughtException’,(err)=>{ //some logic })

@nodepaladin 这种方式会丢失上下文,可能会导致内存爆表啊。

@839305939wang 仔细读一下官方文档,反正我没碰到过,你内存爆表的场景是什么,代码怎么写的

@nodepaladin

var express = require('express');

function external(cb) {
    process.nextTick(function () {
        throw new Error();
        cb.call(null, 'sunny');
    })
}

var app = express();
app.get('/weather', function (req, res) {
    external(function (data) {
        res.end('Weather of Beijing is ' + data);
    })
})
app.listen(8018);


function noop(){}
process.on('uncaughtException', noop)

上面如果出现异常,内存会一直上涨。原因在于noop中没法获取到res对象,res.end 永远不会执行,现有的I/O处于等待的状态,已经开辟的资源不仅不会被释放,而且服务器还在不知疲倦地接受新的用户请求。这样内存是不是有可能爆呢?当然如果异常出现的时候重启的话,这个问题可以避免。

回到顶部