Node.js进修之路15——Domain捕捉毛病

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')
    原文作者:Karuru
    原文地址: https://segmentfault.com/a/1190000013396186
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞