Originally I would like to ask a question about how to create robuts web server based on Node.js. However, that could be a very large and ambiguous question. So I break it to small and concrete question or chanllenge that I am facing when creating a robuts web server.
So, one of the chanllenge I am facing is how to catch all unhandled errors in Node.js? I want to do this becasue I do not want any unhandled error stops Node.js from running which results in web server down.
The solution comes to mind is to put the server running code block in a try-catch block to catch all unhandled errors. however, this is not working if any error happens from an async method. For example my web server could look like below code:
var fs = require('fs');
var http = require('http');
try {
// Here is my main web server, it could happen errors by adding
// more and more modules and functionalities to my server.
// I need to catch all unhandled errors to prevent server from crashing
// So, I put my whole server running in a try-catch block, but any error from
// an async method could not be caught!
http.createServer(function(req, res) {
throw Error("An unhandled error happens!");
}).listen(1234);
}catch (e){
console.log("An unhandled error caught!")
}
console.log('Server is listening to port 1234');
So, am I on the correct direction of error handling to make sure server no stopping? or there is some other mechanism to make server recover from an error?