Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    JavaScript

    How to Creact a React Component Library – Using a Modal Example

    Programming

    5. Уроки Node.js. Глобальные модули.

    JavaScript

    Agile Software Development, Scrum part 2

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Thursday, September 11
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Programming / 23. Node.js Lessons. Domains, asynchronous try.. catch. Part 3.
    Programming

    23. Node.js Lessons. Domains, asynchronous try.. catch. Part 3.

    Ivan RastvorovBy Ivan RastvorovNovember 18, 2016Updated:May 26, 2024No Comments7 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    23. Node.js Lessons. Domains, asynchronous try.. catch. Part 3.
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    23_3

    How and what does app.js consist of?

    It is made in a way that from the very beginning we create a domain and then launch our app within this domain. Here all modules can be connected, a server gets created, etc. But why do we connect modules here? The reason is that some other modules can be added when the connection happens, and they can connect others, too.

    Many of these modules are unfamiliar to me. They are used in some libraries. When modules get created and initialized, some objects can be created – EventEmitters.  I want to be sure these EventEmitters will be connected to server.domain. But the main purpose of this code is to launch http.server:

    server = http.createServer (function(req, res) {
    
           var reqDomain = domain.create();
            reqDomain.add(req);
            reqDomain.add(res);
    
            reqDomain.on('error', function(err) {
              res.statusCode = 500;
              res.end("Sorry, " + err);
               // ...
              serverDomain.emit('error', err);
            });
    
            reqDomain.run(function() {
               handler(req, res);
             });
           });
    
         server.listen(3000);

    Inside a request handler we also create a new domain:

    var reqDomain = domain.create();
            reqDomain.add(req);
            reqDomain.add(res);

    This domain will deal with handling of those errors that occurred with this particular request. Its advantage is that it knows about the request. It contains a handler on.error that can respond: “ 500, sorry, error,” whenever an error occurs. But not only it can respond, but also put into log the current request and the error deriving from it. Thus, as a developer you will see what request you’ve had, and it will be much easier to determine the error and fix it.

    reqDomain.on('error', function(err) {
      res.statusCode = 500;
      res.end("Sorry, " + err);
      console.error('Error for req = ', req);

    We connect objects req and res to the domain as they are EventEmitters and were created within the external Node.js code. That’s why we have to anchor them explicitly.

    Let us imagine handler is in the process. Though an error occurred. We responded to a user: “goodbye, sorry, we’ve got a problem.” Then we included all necessary records into log. We’ve got one server supporting a lot of clients. If those clients had a chance to communicate with each other, an error that occurred somewhere may be rather tough and cause a lot of problems. Note, our domains do not catch all errors here.

    We generally catch errors within callback, try... catch and it is likely some sort of a programming error. Respectively, its existence means the server is in an indefinite state, and it is quite dangerous to leave it like that. That’s why it would be preferable to end this server and initiate a new pure Node.js process. Of course, there may be situation, when you can leave a server working in this state, but let us be more careful for safer results. So, we call

         serverDomain.emit('error', err);

    and thus deliver our work with the error on.error. Note the following detail: domains surely look like try... catch, but they are still different. If we do  throw within  on.error , control is not transferred to serverDomain.on.  Instead, such  throw  will drop out of everything and crash the whole process.

     reqDomain.on('error', function(err) {
              res.statusCode = 500;
              res.end("Sorry, " + err);
              console.error('Error for req = ', req);
                
              throw err;
              serverDomain.emit('error', err);
            });

    So, let us call an external domain exactly via Emit . Further a handler of the external domain will finish handling the error and end the current server process as softly as possible. You can skip the code below:

     if (server) server.close();
    
       setTimeout(function () {
           process.exit(1);
       }, 1000).unref();

    It is graphic. Here we need only domains. We’ve received a working scheme for the inserted error handling. Whether possible, we try to handle errors within the request context:

      reqDomain.on('error', function(err) {
              res.statusCode = 500;
              res.end("Sorry, " + err);
              console.error('Error for req = ', req);
    
              serverDomain.emit('error', err);
            });

    In order to understand at least what request it is and make it easier for a programmer to debug. If an error is more global, it will be caught by serverDomain.on anyway just because it catches almost everything.

    Read More:  Introduction to Micro Frontends: The New Tech on the Block

    Here we could stop, but in this case our attention won’t be comprehensive and close to reality.

    Is it possible that while handling a request below the error that is to appear, will go beyond reqDomainin app.js?

    if (req.url == '/') {  
      
        fs.readFile('no-such-file', function(err, content) {  
      
          if (err) throw err; // JSON.parse("invalid!")  
      
          res.end(content);  
        });  
      
      } else {  
        res.statusCode = 404;  
        res.end("Not Found");  
      }  
      
    }; 
    

    Answer: Yes, it is possible. To demonstrate it, let us modify an example, which refers to older versions of Node.js, while current ones (like 7.1) luckily lack them, as well as the very Domain module as it is considered to be out of date (the example will be needed to understand Legacy Code):

    var domain = require('domain');
    var serverDomain = domain.create();
    
    var server;
    
    serverDomain.on('error', function(err) {
        console.error("Server error", err);
        if (server) server.close();
    
        setTimeout(function () {
            process.exit(1);
        }, 1000).unref();
    });
    
    serverDomain.run(function() {
        var http = require('http');
        var handler = require('./handler');
    
    
        server = http.createServer (function(req, res) {
    
            var reqDomain = domain.create();
            reqDomain.add(req);
            reqDomain.add(res);
    
            reqDomain.on('error', function(err) {
                res.statusCode = 500;
                res.end("Sorry, " + err);
    
                console.error('Error for req = ', req);
    
                serverDomain.emit('error', err);
            });
    
            reqDomain.run(function() {
                handler(req, res);
            });
        });
    
        server.listen(3000);
    });

    In handler.js we’ve got a database. It can be MongoDB, MySQL, Redis (you need to have Redis installed on your PC and its client, which can be installed using:

    npm install redis 

    the database itself need to be installed separately.

    They all have the same problem working with the domain.

    //var database = require ('mongodb');
    //var mysql = require ('mysql');
    var redis = require('redis').createClient();
    
    module.exports = function handler(req, res) {
        if (req.url == '/') {
    
            redis.get('data', function(err, data) {
    
                throw new Error("redis callback"); //
    
            });
    
        } else {
            res.statusCode = 404;
            res.end("Not Found");
        }
    
    };

    In order to give a response to a visitor, you need to send a request to the database.
    Then we need to do something with the data – probably, handle them or send other requests. Anyway, we’ve got an error somewhere. Where will it go to? Launch and move to the page:

    Read More:  18. Node.js Lessons. Work With Files. Fs Module

    127.0.0.1:3000

    We see the connection has been broken. Server error is what a domain outputs below:

    serverDomain.on('error', function(err) {
        console.error("Server error", err);
        if (server) server.close();
    
        setTimeout(function () {
            process.exit(1);
        }, 1000).unref();
    });

    It means, throw new Error ("redis callback") was never caught by a handler:

            reqDomain.on('error', function(err) {
                    res.statusCode = 500;
                    res.end("Sorry, " + err);
    
                    console.error('Error for req = ', req);

    it moved immediately to the upper part. Why? The error occurred in the process of work of the handler function handler(req, res) , so how did it happen that it derived from requestDomain ?

    In order to answer this question, we need to remember: there are only 2 ways how a domain gets transferred to the callback of asynchronous calls. The first one is an internal Node.js method: built-in setTimeout, fs.readFile and so on. They are integrated with the domains and share them further to callback. The seconds one deals with various  EventEmitters. If EventEmitte was created in the domain context, it gets anchored to it.

    The redis.get method we call here uses the redis object that was created outside the request context, when connecting the module. It is a standard practice within Node.js, when one connection is used for many requests. Respectively, if we want to get some data, we give something we need to receive (data) to the redis object and some callback. Further this object does something, sends something to the database and has got internal EventEmitters created together with it to generate events, once a database responds something. And these internal EventEmitter will transfer a domain when generating events. But what domain? Of course, the one they were created with, which means an external domain from app.js :

    serverDomain.run(function() {.....});

    It will come out this callback will be called in serverDomain and won’t save the request context. Next, if this callback calls some other functions, we will get the same domain, and requestDomain will get lost for us.

    So, what should we do? There are 2 options. The first one is to create a special call process.domain.bind.

     redis.get('data', process.domain.bind(function(err, data) {
    
                throw new Error("redis callback"); 
    
            }));

    This call rotates a wrapping around the function that anchors it to the current active domain, i.e. the request domain. If we launch our domain today, everything will be ok. (Everything will work perfectly without this record in the current Node.js version, too, but you may meet the following record for older versions, too)
    Everything we needed has worked. You will see in your browser:
    Sorry, Error: redis callback;

    The lesson code can be found here

    23_end

    The materials for the article were borrowed from the following screencast

    We are looking forward to meeting you on our website blog.soshace.com

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Ivan Rastvorov
    • Website

    Related Posts

    Mastering REST APIs: Essential Techniques for Programmers

    December 18, 2024

    Crafting Interactive User Interfaces Using JavaScript Techniques

    December 17, 2024

    Effective Strategies for Utilizing Frameworks in Web Development

    December 16, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    JavaScript January 28, 2020

    Fermentum Dui Faucibus Bnornare Quam Viverra Orci

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore…

    Markdown Cheat Sheet: Definitive Guide to Markdown + Markdown Resources

    September 16, 2019

    Public Speaking for Developers Demystified: Tips & Tricks

    July 29, 2019

    How to Architect a Node.Js Project from Ground Up?

    December 19, 2019

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    React Lesson 13 Part 2: Asynchronous actions

    JavaScript July 6, 2020

    Create simple POS with React.js, Node.js, and MongoDB #7: Adding redux to other components

    JavaScript June 22, 2020

    What Is Responsive Web Design?

    Beginners May 13, 2019

    How I Built an Admin Dashboard with Python Flask

    Beginners August 2, 2020

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    Programming

    Python range() Explained and Visualized

    JavaScript

    Build Real-World React Native App #9 : Implementing Remove Ads Feature

    Beginners

    Top 10 Bug Tracking Tools for Web Developers and Designers

    Most Popular

    9. Уроки Node.js. События, EventEmitter и Утечки Памяти

    Programming

    Enhancing Software Development: The Crucial Role of Version Control

    Development

    Knowledge is a power

    JavaScript
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.