Updated March 31, 2023
Introduction to Node.js Error Handling
Error handling is the process of catching and processing errors efficiently. These errors may be synchronous or asynchronous. Error handling is a core part of any programming language. As we know node.js is nothing but the JavaScript runtime for the server. Node.js Mainly works on how we handle errors coming in a flow. We are familiar with other programming language error handling. Mostly we have seen try and catch block to handle the error.
function a(b) {
try {
logic ((err) => {
if (error) {
throw (error);
}
` });
} catch (e) {
b(e);
}
}
Above is the kind of error handling we have seen.
Importance of Error Handling
To understand error handling in node.js we should know some key concepts like callback functions, Asynchronous functions like a promise, and async-await, try.. catch block, throw keyword, error object.
If you ever wonder why we need to concentrate on node.js, then look at an example.
Suppose you are getting requests from the client. And you have to send a proper response back to the client. The client does not know the internal details of the program, but he should understand in an easy way that something went wrong. At this point, we should give a proper response by handling errors.
Throwing and catching errors on time is very important.
How does Error Handling work in Node.Js?
First, we are going to see try-catch with node.js. With this, we are going to use the error object.
function a() {
b();
}
function b() {
throw new Error('Something went wrong');
}
function errorCheck() {
try {
a();
} catch(e) {
console.log(e);
}
}
errorCheck();
Output:
In node.js we are catching errors and showing the appropriate results to the client. In the above program, we are defining function a. In function a, we are calling function b. Function b has an error object which throws an error by passing the parameter to catch. In errorCheck() function we have to try-catch block to handle errors efficiently.
In node.js we are specifically dealing with api calls. With the express, we need to handle errors. We can handle errors in express synchronously and Asynchronously.
Synchronous way to catch errors is as follows
app.get('/', function (req, res) {
throw new Error("Something went wrong")
})
Asynchronous way to catch errors
app.get('/', function (req, res, next) {
fs.readFile('/fileNotFound', function (err, data) {
if (err) {
next(err)
} else {
res.send(data)
}
})
})
Examples to Implement Error Handling Node.Js
Here are the following examples mention below
Example #1
Handling Node.js Errors when Using Promises
function a() {
return Promise.resolve('Hello World');
}
function b(){
console.log("Promise is not resolved here")
}
a()
.then(b)
.catch((e) => {
})
Output:
Example #2
Handling Node.js errors with express
Express has the ability to handle errors by default.
Example:
app.get('/', [
function (req, res, next) {
fs.writeFile('/home', 'data', next)
},
function (req, res) {
res.send('OK')
}
])
Till now you have seen that we are just writing the code and throwing that error which is probably known to us. We are not handling that efficiently. In node.js we mostly use asynchronous programming. In asynchronous try-catch error handling not going to work effectively.
We are working with file handling in node.js mostly. Fs i.e. file handling is the core module in node.js. Let’s take an example of this.
Example: We are going to save this file as nodeFile. And on the same location, you have to create index.txt file.
var fs = require("fs");
fs.readFile("index.txt","utf8",function(error, value)
{
if(error){
throw error;
}
console.log(value);
});
process.on("e",function(error){
console.log("There is an exception")
});
Save the above code in some folder. Also, make sure that you are making the text file that we mentioned in the program. Index.txt is the file we going to read in this program.
Type the command in the command prompt i.e node name of the file.
Example: node nodeFile
Output:
In the above program, we caught an exception, and without showing the exact error to the end-user we handled that error. This is a very useful way to save our program by crashing. End-user is not at all concerned about what is going on at the background of the program. This concept is called handling errors in node.js.
Points to Remember while Working with Error Handling
- It is a programmer’s responsibility to throw the errors at the appropriate place.
- All the necessary arguments have to be matched with the function. If any known discrepancies we got in between then we have to handle it at the program level.
- We need to observe is there a need to emit the error or handle it.
- Our errors have to come up with efficient details so that the next person who is going to come across that error can get an idea to deal with that error.
- We are decision-makers for handling unexpected errors. We should know where to use try-catch or throw an exception.
- You should know what is the probability of errors while working with node.js.
- We have to focus on the pattern and recommendation for the specific programs.
- Need to be clear about functional logic.
- Try to use of error object in node.js.
- You need to practice to know what kind of errors we are getting. Getting the exact context of error helps you to manage it efficiently.
Further, there are two types of errors we can say. Operational errors and programmer errors.
In such situations, documentation comes into the picture. if you are trying to build something have a habit to write the appropriate comments for that code. So the next programmer can easily understand the code flow and can manage errors effectively.
All our motto is at the end to minimize the errors. To take some precautions while writing the code.
Conclusion
To handle error efficiently you should familiar with the Javascript ES5 and ES6 syntax and its usage. In the end, the node is nothing but the javascript on the server-side. Javascript has an error handling concept. If you are familiar with those concepts then you can easily handle errors in node.js.
Recommended Articles
This is a guide to Node.js Error Handling. Here we discuss the Examples to Implement Error Handling Node.Js and How does it work. You may also have a look at the following articles to learn more –