Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle all exceptions in node.js

After working for a couple of weeks with node.js, I found that there is a difference between node.js server errors and regular server side languages like PHP.

A simple example: IF an error happens in our website for ANY reason.

in PHP
If a user send some invalid data to server and MySQL, MySQL will output error to that specific user and the whole application won't go down.

in Nodejs
If a user send some invalid data to server and MySQL, nodejs Server will go down and so all the users will disconnect and there is no connection between users anymore.

This is a really big problem. in large web applications, It is impossible to handle all errors to avoid Nodejs server to go down, and the question is,
Is there any way to handle any unknown fatal errors and exceptions to a specific output or something like it.

like image 566
Pars Avatar asked Nov 11 '13 15:11

Pars


People also ask

How do you handle all exceptions?

The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.

How do I log exceptions in node JS?

An example would be; process. on('uncaughtException', function (err) { if (err) { console. log("caughtException but no error msg" + err.

What is exception in node JS?

The exception handling refers to the mechanism by which the exceptions occurring in a code while an application is running is handled. Node. js supports several mechanisms for propagating and handling errors.


1 Answers

You can use the uncaughtException event on the process object to do what you want, but like others have said, domains and catching/handling errors at the correct level is recommended.

process.on('uncaughtException', function(err) {   console.log('Caught exception: ' + err); }); 
like image 126
BadCanyon Avatar answered Sep 24 '22 05:09

BadCanyon