Node.js – Error Handling: Errors are part of every programming language, and Node.js Environment is not an exception. There are many predefined errors in Node.js, including errors like SyntaxError, RangeError, and many more. The official documentation of Node.js has provided a detailed description of the Errors. However, the point to be noted is that this documentation also refers to the Exceptions. So, let just not be confused with Errors over Exceptions.


Exceptions are the values thrown as the Output of the Invalid Operations or as the throw statements’ targets. Therefore, all exceptions thrown by the JavaScript runtime or Node.js will be the instances of Errors. Thus, we will be handling errors as exceptions in Node.js.
Firstly, it is essential to have a clear understanding of errors in Node.js. Generally, the errors in Node.js are classified into two different categories. The First one is Operational errors, and the other is Programmer errors, respectively.
To Understand the concept of Error Handling, let’s start with creating exceptions.
To create an exception, we use the ‘throw’ keyword following the value:
Once JavaScript executes the above line, the normal flow of the program stops, and the control is held back to the closest exception handler. Any JavaScript value used as the client-side code value can be a number, a string, or an object.
Note: Generally, we throw Error objects in Node.js instead of throwing any strings.
Error objects capture a “stack trace” specifying the point in the code at which the Error was instantiated and may give a text description of the Error.
All the errors created by Node.js, including JavaScript and all system errors, will either be inherited from or instances of the Error class provided in the Error core module:
or
The try/catch statement is used as an exception handler. The corresponding catch block handles any exception that appear
s in the code line’s syntax comprised in the try block.
To catch various types of errors, we can add multiple handlers.
The program will crash if an uncaught exception gets thrown when the program is being executed. The uncaughtException event is used in the process object to solve such a situation.
We don’t have to import the built-in process module for the procedure, as it’s injected automatically.
We can use promises to chain different operations and handle the errors at the end:
So, a question pops up in one’s head is: How do we know where the Error occurred? Well, we don’t know, but whenever we call (doOperationX), we can handle errors in each of the functions and can be called outside of the catch handler by throwing a new error in the error handler:
We can break the chain without handling the errors in the function we call but, locally, we can process the exception by creating a function in each then():
We still need to catch errors while using async/await in the following manner:

source