Error Handling in Node js

Error handling is a pain, and it’s easy to get by for a long time in Node.js without dealing with many errors correctly. But building robust Node.js(Node js) apps requires dealing properly with errors, and it’s not hard to learn how.
Node.js follows a callback pattern where an error object is the first argument and data is the second argument.
By default, when a runtime error occurs in an Express app, it will either be caught by the error handler defined in the router middleware or it will bring down the server.

    var http = require('http');
    var express = require('express');
    var app = express();
       app.get('/', function (req, res) {
        // Error will be caught
      get_data();
    });
var port = 3000;
app.listen(port);
console.log('Listening on port ' + port);

When you load http://localhost:3000/, you will get 500 Internal Server Error,but the server is still up and running, and users can still access the functional parts of the app.

Also there is another example of an uncaught error, which brings down the server.

 
    app.get('/', function (req, res) {
       // An async operation which causes an error
    process.nextTick(function() {
      get_data();
    });
  });

process.nextTick() is a low-level construct to execute instructions after the current set of instructions have been processed, making all the expressions within it asynchronous relative to the current set. You can read more about process.nextTick()
This time, when you load http://localhost:3000/, the app will crash instantly.

About

My Name is Dileep Singh, Noder, Javascript Lover & NoSql Developer, Fitness Freak, Love to travel new places, learning photography & Music Manic ♯ ♩ ♬

Posted in Express, Node.Js Tagged with: ,
One comment on “Error Handling in Node js
  1. Tanisha says:

    Everything is very open with a clear description of the issues.
    It wwas definitely informative. Your site is useful. Many
    thanks foor sharing!