Understanding the different error types and handling in Node.js


Error types are −

  • Syntax error

  • Runtime error

  • Logical error

Syntax error −

These are easy to find as most of the development tools like visual code studio shows red lines whenever there is a syntax error. The suggestion for resolution may be not be correct in tools but it gives an idea of what went wrong in a specific area of code.

On running an app, console terminal will shows the errors. Console log can point to exact line where error occurred.

More common syntax error are like missing closing bracket for a block , it will need to identify correct blocks .

Runtime error −

Example − If we miss a return keyword before a sending a response like below −

return req.on('end', ()=>{
   const parsedData = Buffer.concat(requestBody).toString();
   const username = parsedData.split('=')[1];
   fs.writeFile('username.txt', username, (error)=>{
      console.log(error);
   });
   //redirect
   res.statusCode=302;
   res.setHeader('Location','/');
   res.end();
});

In above code, we just have res.end() but if any code below end (0 function changes response object it will result into an error at runtime.

Runtime errors are difficult to find at compile time of code.

Logical error −

Logical error are difficult than runtime to find cause. Because in most of the scenarios, it wont even shows a error message but app does not functions in a way which was required.

To solve the issues in logical error, we require debugging of application.

To use debugger select App.js file and from tabs select Run->Start Debugging

We will get a debug console window as well. Now add breakpoints at lines where we want to debug code.

When we get a request and it reaches to breakpoint we can inspect code . Code inspection helps in finding logical error and can be corrected easily.

On debug we can see values of variables and can change it too. Below snapshot shows the some of the options available in debug mode.

Updated on: 13-May-2020

272 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements