Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

handle uncaughtException in Express and Restify

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?

Problem courtesy of: Zhe


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    
    //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 :)

Solution courtesy of: Benjamin Gruenbaum


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

handle uncaughtException in Express and Restify


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription