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

node-24-part_1

Hey all! Our topic for today is Domains.

Domains are one of the Node.js options lacking both in standard JavaScript and browser versions of JavaScript. Domains were created to catch any asynchronous errors. For instance, if we look at the server that we’ve explored in one of our previous articles (download the lesson code from here for your convenience), we will see that everything is ok when it’s working

But whenever some program error occurs – let’s imagine, a call of  an unknown function:

or a user puts throw instead of handling the error:

Or some sort of a program error – for example, a call of  JSON.parse("invalid!") with  invalid JSON, which crashes the whole process in the end. It turns out, we’ve got a server with 1000 clients connected to it, and a program error occurs when handling a request from one of them:

The current state leads to a crash of the whole process. Of course, it is bad because every process crash means a connection failure for all previously connected clients. If a server crashes, let us at least handle it in a proper way, show a message that an error occurred, and only after it, if the error is crucial, we can intercept the process. But this task is quite difficult, even though being essential and obligatory for to be solved.

For the reason callbacks function(err, content) are called asynchronously, wrapping in try... catch is generally absolutely ineffective here. So, let us add this record to our code instead of the current one:

Even if we call a handler inside try... catchit will be able to catch only those errors present for the current work of a handler function. But if there are some asynchronous callbacks, they are not included.

Now, when we know something about the problem, let us talk about possible ways to solve it in Node.js. To do so, we need to use a module named domain. At the moment, this module is obsolete and using it in the current version of Node.js (7.1) is not recommended. Our articles about domains will be useful for understanding and working with Legacy Code for example. It will enable us to create a special object called a “domain” – for example, serverDomain, and let us add it to our server.js:

In the domain  context you can launch functions, and it will catch any possible error, including an asynchronous one, which may happen within the function or one derived from it. As an example, let us do some refactoring of the current code inside the file server.js by completing export of the server, and launch it from the other domain-contained file:

A new file being launched will be called app.js, add it to the root directory. It will create a domain object and connect a server:

A server is simply being exported from the file server.js. It means, it doesn’t launch a server at the moment, but simply creates it.

Next we install a domain handler in app.js

Any error that will occur inside the domain will be caught by this function. And, finally, the most important thing – let us launch a server inside the domain using a special call named run:

Now any error occurring as a result of work of a previous function or a function derived from it, including handlers, will be caught. So, let us launch a project and then launch it once again. As the address is already occupied, it led to an error, which means a server showed an error event:

Domain has caught Error: listen EADDRINUSE :::3000

For the reason there were no handlers for this errorthis event would lead to an exception that would fail the process, but now it is successfully caught by the domain.

Let us try to access an unknown file:

Launch app.js, follow this url in Chrome:

http://127.0.0.1:3000/

Enter. Error. That’s what has happened: for some reason we’ve got an exception, our domain didn’t work. Why? Here we see one of the downsides domains have. To understand and fix it, let us see how domains work and why domain failed in this situation. It will be easier to understand domains, if we look at a couple of simple examples followed by a more complex example, instead of one too complicated case. So, let us create domain.js with this code (other files may be deleted):

Here in domain we see a function launched, and we don’t know exactly what it calls. So, launch it. Domain caught an error:

How did it manage to do it? Everything’s quite simple. Whenever a function is called in d.run, it is surrounded by implicit try catchRespectively, any exception derived from this function immediately turns into an error:

That is the most trivial case. But let us study something more difficult by changing our code in domain.js in the following way:

Here the same function with an error is called inside setTimeout. So, check whether it works. It does! But how does this function inside setTimeout get to know it is launched inside the domain? You can answer this question, if you look inside Node.js. When a function is launched in the domain context, there occurs a special call inside the domain  module before the launch:

d.enter();

and a call in the end,

//d.exit();

or the domain enter and exit:

And this:

will work asynchronously one day. It will get a domain for the reason that whenever we enter the domain, its current object becomes global. It looks just like that:

And setTimeoutjust like a number of other Node.js modules responsible for various asynchronous things, is integrated into domains. It means, the setTimeout  internal implementation analyzes whether there is an active current domain, and upon calling the function it guarantees the very domain will be active. So, if you create a console inside the function:

We will get it by launching domain.js:

Note, it is a standard object that inherits EventEmitter.

To be continued!

The lesson code can be found here.

futurecontinued

The materials for this article were borrowed from the following screencast.

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

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter the correct name.
Please enter the correct email.
Looks good!

Related articles

15.03.2024

JAMstack Architecture with Next.js

The Jamstack architecture, a term coined by Mathias Biilmann, the co-founder of Netlify, encompasses a set of structural practices that rely on ...

19.01.2024

Training DALL·E on Custom Datasets: A Practical Guide

The adaptability of DALL·E across diverse datasets is it’s key strength and that’s where DALL·E’s neural network design stands out for its ...

12.06.2023

The Ultimate Guide to Pip

Developers may quickly and easily install Python packages from the Python Package Index (PyPI) and other package indexes by using Pip. Pip ...

0 comments

Sign in

Forgot password?

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy