Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handle uncaughtException in Express and Restify

I use both restify and express.

In restify, I create server in this way:

server = restify.createServer(serverSettings);

Then, I can handle uncaughtException like this:

server.on('uncaughtException', function(req, res, route, err) {})

It's different with process.on('uncaughtException'). Because it's caught all uncaughtException and can give a response to client. So I like this way to catch the exception.

But in Express, I can't find something like this.

So just want to ask, is there a same thing in express? or there are some way I can implement the same function?

like image 683
Zhe Avatar asked Jul 30 '13 07:07

Zhe


1 Answers

Update 2014: In retrospect, NodeJS domains are kind of unstable and quirky. They produce a lot of edge cases and are not a lot of fun. Promises are likely a better option for error handling - good promise libraries like Bluebird and Q produce good stack traces and Bluebird is fast - promises also have a catch safety guarantee.

Update 2017: You should definitely be using async functions for anything asynchronous you're doing that is one time and use that for exception handling and use language built in tools like async iterators for exception handling. The days of writing callback soup are long gone by now.


Use domains.

Domains were introduced in version 0.8 and are being worked on so they're pretty new. In 0.10 they're pretty steady. They provide a preferably approach to a "uncaughtException" event. Domains are awesome deprecated :D. It's not specific to express, or any other specific framework or library.

Generally speaking, domains lets you do code separation. Everything you start in a domain will let the domain catch it. They let you get concise stack traces and tell the server what to do when an error occurs. You can even use domains for specific parts in the server although keep in mind exceptions are relatively expensive things in the JS world.

var d = domain.create();
d.on('error', function(er) {
   //your handler here    
});
d.run(function(){
    //create the server here, 
    //errors thrown will be handled by the domain handler
});

I've also written a simple try/catch for asynchronous exceptions here in case you find that interesting :)

like image 67
Benjamin Gruenbaum Avatar answered Nov 10 '22 15:11

Benjamin Gruenbaum