I'm currently working on a node.js app and I'm having the usual asynchronous code issue.
I'm implementing a service server on top of Node's HTTP module.
This server supports (express like) routes. For example I have code that looks like this:
server.any("/someRoute",function(req,resp){
resp.end("this text is sent to clients via http")
});
The server needs to be able to withstand failure, I do not want to crash the whole server when there is a problem in a function passed to any. The problem occurs when I'm writing code that looks like:
server.any("/someRoute",function(req,resp){
setTimeout(function(){
throw new Error("This won't get caught");
},100);
});
I don't see how I possible can catch the error here. I don't want to crash the server over one server-side glitch, instead I want to serve 500.
The only solutions I've been able to come up with are really not expressive. I've only come up with using process.on("uncaughtException",callback)
and similar code using node 0.8 Domains
(which is a partial remedy but Domains are currently buggy and this is still not very expressive since I end up having to create a domain for every handle).
What I would like to accomplish is binding throw
actions from a function to a scope, the ideal solution is something like binding all thrown errors from a function to a specific handler function.
Is this possible? What is the best practice to handle errors in this case?
I'd like to emphasise that it should be able to continue serving requests after a bad requests, and restarting the server on every request or creating domains for every handler and catching their uncaught exceptions seems like a bad idea to me. Additionally - I've heard promises might be able to assist me (something about throw
in promises), can promises aid me in this situation?