var domain = require('domain');
//引入一个domain的中间件,将每一个请求都包裹在一个独立的domain中
//domain来处理异常
app.use(function (req,res, next) {
var d = domain.create();
//监听domain的错误事件
d.on('error', function (err) {
logger.error(err);
res.statusCode = 500;
res.json({sucess:false, messag: '服务器异常'});
d.dispose();
});
d.add(req);
d.add(res);
d.run(next);
});
inherits(Domain, EventEmitter);
function Domain() {
EventEmitter.call(this);
this.members = [];
}
Domain.prototype.enter = function() {
if (this._disposed) return;
// note that this might be a no-op, but we still need
// to push it onto the stack so that we can pop it later.
exports.active = process.domain = this;
stack.push(this);
_domain_flag[0] = stack.length;
};
Domain.prototype.exit = function() {
// skip disposed domains, as usual, but also don't do anything if this
// domain is not on the stack.
var index = stack.lastIndexOf(this);
if (this._disposed || index === -1) return;
// exit all domains until this one.
stack.splice(index);
_domain_flag[0] = stack.length;
exports.active = stack[stack.length - 1];
process.domain = exports.active;
};
process._fatalException = function(er) {
var caught;
if (process.domain && process.domain._errorHandler)
caught = process.domain._errorHandler(er) || caught;
if (!caught)
caught = process.emit('uncaughtException', er);
// If someone handled it, then great. otherwise, die in C++ land
// since that means that we'll exit the process, emit the 'exit' event
if (!caught) {
try {
if (!process._exiting) {
process._exiting = true;
process.emit('exit', 1);
}
} catch (er) {
// nothing to be done about it at this point.
}
// if we handled an error, then make sure any ticks get processed
} else {
NativeModule.require('timers').setImmediate(process._tickCallback);
}
return caught;
};