23. Node.js Lessons. Domains, asynchronous try.. catch. Part 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:

Inside a request handler we also create a new domain:

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.

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

and thus deliver our work with the error on.errorNote the following detail: domains surely look like try... catchbut 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.

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:

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:

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.

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?

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):

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.

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:

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

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

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 callbackThe seconds one deals with various  EventEmittersIf 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 callbackFurther 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 :

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.

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


The materials for the 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

Managing Kubernetes using Terraform

Kubernetes has continued in its strive to influence the tech space with its flexibility and portability in container orchestration. And with its ...

Handling GraphQL API Authentication using Auth0 with Hasura Actions

In this article, we’re going to demonstrate how we can set up Authentication/Authorization with Hasura and Auth0. First, we’ll set up the Auth0 ...

Building Rest API With Django Using Django Rest Framework and Django Rest Auth

Building Rest API seems to be complex when trying to achieve this on your own with Django,  thanks to the Django Rest framework project which has ...

No comments yet

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