当前位置: 首页 > 后端技术 > Node.js

Node.js学习之路15——域捕获错误

时间:2023-04-03 16:02:34 Node.js

1.捕获错误try...catch机制无法捕获异步方法抛出的错误uncaughtException时间可以捕获任何未处理的错误,但可能会导致内存泄漏等2.域模块出错使用domian模块中的create方法创建域object,vardomain=domain.create(),create方法没有参数,该方法返回创建的Domain对象。该对象是继承EventEmitter类的实例对象。当对象捕获到任何错误时,将触发对象的错误事件。捕获到错误时的处理可以通过监听对象的错误事件并指定事件回调函数来实现。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();consthttp=require('http');constdomain=require('domain');constprocess=require('process');http。createServer(function(req,res){vard=domain.create();d.name='domainOne';d.once('error',function(err){res.writeHead(200,{'Content-Type':'text/html'});res.write('')res.write('服务端接收到客户端出现如下错误request:')res.end(err.message);})d.run(function(){if(req.url!=='/favicon.ico'){notexitsfunction();//这是一个错误res.writeHead(200,{'Content-Type':'text/html'});res.write('')res.end('你好');}process.nextTick(()=>{setTimeout(()=>{fs.open('./notExistFile.txt','r',(err,fd)=>{if(err){扔呃;}})})})})}).listen(2576,'localhost')