1. 捕捉毛病
-
try...catch
机制不能捕捉异步要领抛出的毛病 -
uncaughtException
时刻能够捕捉任何未被处置惩罚的毛病,然则能够会引起内存走漏等状况
2. domain
模块猎取毛病
运用domian模块中的create
要领建立一个domain
对象,var domain = domain.create()
,create
要领没有任何参数,该要领返回被建立的Domain
对象。该对象是一个继续了EventEmitter
类的实例对象,当该对象捕捉到任何毛病时,触发该对象的error
事宜。能够经由过程监听该对象的error
事宜并指定事宜回调函数的要领来完成当捕捉到毛病时的处置惩罚。domain.on('error', function(err){})
domain
模块中,为Domain
对象定义了一个name属性值,能够运用该属性值来设置或猎取该Domain
对象的称号。
在Domain对象被建立后,须要指定该对象所监听的代码,我们须要将这些代码书写在一个函数中,而且运用Domain对象的run要领指定Domain对象监听该函数中的代码。当这些代码触发任何毛病时,将被Domain
对象捕捉。Domain
对象的run
要领的指定要领以下domain.run(fn)
在Domain
对象的run
要领中,运用一个参数,参数值为一个函数,当该函数中触发任何毛病时,将被Domain
对象捕捉。
当Domain
对象不再须要的时刻,能够烧毁d.dispose();
示例
const http = require('http');
const domain = require('domain');
const process = require('process');
http.createServer(function (req, res) {
var d = domain.create();
d.name = 'domainOne';
d.once('error', function (err) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<head><meta charset="utf-8"/></head>')
res.write('服务器端吸收客户端要求时发作以下毛病:')
res.end(err.message);
})
d.run(function () {
if (req.url !== '/favicon.ico') {
notexitsfunction(); //this is an error
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<head><meta charset="utf-8"/></head>')
res.end('hello');
}
process.nextTick(() => {
setTimeout(() => {
fs.open('./notExistFile.txt', 'r', (err, fd) => {
if (err) {
throw err;
}
})
})
})
})
}).listen(2576, 'localhost')