How to handle code exceptions in node.js?

I went through the documentation of Express, and the part describing error handling is completely opaque to me.

I figured the app they're referring to is an instance createServer(), right? But I have no clue how to stop node.js from blowing up the application process when an exception occurs during handling a request.

I don't need anything fancy really; I just want to return a status of 500, plus an otherwise empty response, whenever there's an exception. The node process must not terminate just because there was an uncaught exception somewhere.

Is there a simple example of how to achieve this?


var express = require('express');
var http = require('http');

var app = express.createServer();

app.get('/', function(req, res){
    console.log("debug", "calling")
    var options = {
        host: 'www.google.com',
        port: 80,
        path: "/"
    };
    http.get(options, function(response) {
       response.on("data", function(chunk) {
           console.log("data: " + chunk);
           chunk.call(); // no such method; throws here
       });
    }).on('error', function(e) {
       console.log("error connecting" + e.message);
    });
});

app.configure(function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.listen(3000);

crashes the entire app, producing traceback

mypath/tst.js:16
           chunk.call(); // no such method; throws here
                 ^ TypeError: Object ... has no method 'call'
    at IncomingMessage.<anonymous> (/Library/WebServer/Documents/discovery/tst.js:16:18)
    at IncomingMessage.emit (events.js:67:17)
    at HTTPParser.onBody (http.js:115:23)
    at Socket.ondata (http.js:1150:24)
    at TCP.onread (net.js:374:27)

If you really want to catch all exceptions and provide some handling other than exiting the Node.js process, you need to handle Node's uncaughtException event.

If you think about it, this is a Node thing, and not an Express thing, because if you throw an exception from some arbitrary piece of code, there's no guarantee Express can or will ever see it, or be in a position to trap it. (Why? Exceptions don't interact very well with asynchronous event-driven callbacky code that is the Node style. Exceptions travel up the call stack to find a catch() block that's in scope at the time the exception is thrown. If myFunction defers some work to a callback function that runs when some event happens, then return to the event loop, then when that callback function is invoked, it's invoked directly from the main event loop, and myFunction is no longer on the call stack; if this callback function throws an exception, even if myFunction has a try/catch block, it's not going to catch the exception.)

What this means in practice is that if you throw an exception and don't catch it yourself and you do so in a function that was directly called by Express, Express can catch the exception and call the error handler you've installed, assuming you've configured some piece of error-handling middleware like app.use(express.errorHandler()). But if you throw the same exception in a function that was called in response to an asynchronous event, Express won't be able to catch it. (The only way it could catch it is by listening for the global Node uncaughtException event, which would be a bad idea first because that's global and you might need to use it for other things, and second because Express will have no idea what request was associated with the exception.)

Here's an example. I add this snippet of route-handling code to an existing Express app:

app.get('/fail/sync', function(req, res) {
   throw new Error('whoops');
});
app.get('/fail/async', function(req, res) {
   process.nextTick(function() {
      throw new Error('whoops');
   });
});

Now if I visit http://localhost:3000/fail/sync in my browser, the browser dumps a call stack (showing express.errorHandler in action). If I visit http://localhost:3000/fail/async in my browser, however, the browser gets angry (Chrome shows a "No data received: Error 324, net::ERR_EMPTY_RESPONSE: The server closed the connection without sending any data" message), because the Node process has exited, showing a backtrace on stdout in the terminal where I invoked it.

Error Handling in Node.js, If there were, you would have just used the error handling code in place of the code that caused the error! This distinction is very important: operational errors are  Approach 1: Using try-catch block: We know that Node.js is a platform built on JavaScript runtime for easily building fast and scalable network applications. Being part of JavaScript, we know that the most prominent way to handle the exception is we can have try and catch block.

To be able to catch asynchronous errors I use domain. With Express you can try this code:

function domainWrapper() {
    return function (req, res, next) {
        var reqDomain = domain.create();
        reqDomain.add(req);
        reqDomain.add(res);

        res.on('close', function () {
            reqDomain.dispose();
        });
        reqDomain.on('error', function (err) {
            next(err);            
        });
        reqDomain.run(next)
    }
}
app.use(domainWrapper());
//all your other app.use
app.use(express.errorHandler());

This code will make your asynchronous error be captured and sent to your error handler. In this example I use the express.errorHandler, but it works with any handler.

For more information about domain: http://nodejs.org/api/domain.html

Node.js Best Practice Exception Handling, Safely "catching" errors. Sometimes though, there may still be code that throws an error somewhere which can lead to an uncaught exception and a potential crash  How Node.js handles exceptions. When a function in Node is called, it is typically passed a callback argument which is executed when the operation completes. This callback pattern is ubiquitous across Node.js applications because it is harmonious with the event loop.

You can use the default error handler that express uses, which is actually connect error handler.

var app = require('express').createServer();

app.get('/', function(req, res){
  throw new Error('Error thrown here!');
});

app.configure(function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.listen(3000);

Update For your code, you actually need to capture the error and pass it to express like this

var express = require('express');
var http = require('http');

var app = express.createServer();

app.get('/', function (req, res, next) {
  console.log("debug", "calling");
  var options = {
    host:'www.google.com',
    port:80,
    path:"/"
  };
  http.get(options,
    function (response) {
      response.on("data", function (chunk) {
        try {
          console.log("data: " + chunk);
          chunk.call(); // no such method; throws here

        }
        catch (err) {
          return next(err);
        }
      });
    }).on('error', function (e) {
      console.log("error connecting" + e.message);
    });
});

app.configure(function () {
  app.use(express.errorHandler({ dumpExceptions:true, showStack:true }));
});

app.listen(3000);

Error handling in Node.js, Usually in client-side code value can be any JavaScript value including a string, a number or an object. In Node.js, we don't throw strings, we  Exception Handling in Node 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.

express 5.0.0-alpha.7 came out 27 days ago. With this very specific pre-release version, you can now finally reject a promise inside a request handler and it will be handled properly:

Middleware and handlers can now return promises and if the promise is rejected, next(err) will be called with err being the value of the rejection. (source)

For example:

app.get('/', async () => {
    throw new Error();
});
app.use((err, req, res, next) => {
    res.status(500).send('unexpected error :(');
});

However, only use this as a fallback. Proper error handling should still happen inside catch-phrases inside the request handlers themselves with proper error status codes.

Exception Handling in Node, 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  Node.js has 3 basic ways to handle exceptions/errors: try-catchblock. erroras the first argument to a callback. emitan errorevent using eventEmitter. try-catchis used to catch the exceptions thrown from the synchronous code execution. If the caller (or the caller's caller, ) used try/catch, then they can catch the error. If none of the callers had try-catch than the program crashes.

Node.js Error Handling Explained, Find out useful Node.js modules for dealing with errors and best Programmer errors are bugs and should be dealt with in your code. This is  As soon as JavaScript executes this line, the normal program flow is halted and the control is held back to the nearest exception handler. Usually in client-side code value can be any JavaScript value including a string, a number or an object. In Node.js, we don’t throw strings, we just throw Error objects.

Errors, error.address; error.code; error.dest; error.errno; error.info; error.message All JavaScript errors are handled as exceptions that immediately generate and  Promises handle errors quite elegantly and will catch any errors that preceded it in the chain, which is great for Node.js programmers, because it means that we can handle many errors in many functions in a single handler.

Error Management in Node.js Applications, Not handling async errors properly. Error handling in asynchronous code is quite different and even tricky if you are not quite familiar with the  Promises are ubiquitous in Node.js code and sometimes chained to a very long list of functions that return promises and so on. Not using a proper .catch(…) rejection handler will cause an unhandledRejection event to be emitted, and if not properly caught and inspected, you may rob yourself of your only chance to detect and possibly fix the

Comments
  • just because there was an uncaught exception somewhere. The process will die if there is an uncaught exception. If you don't want it to terminate when an exception occurs, catch the exception and return 500 error.
  • You might be interested in the non-express way: stackoverflow.com/questions/4213351/…
  • Excellent, thanks a lot @Matt !
  • This is a truly excellent answer because it is not only illuminating in its clarity of how express catches stray exceptions and handles them with error middleware (which is an unexpected default behavior ), but also because it explains how using 'throw new Error("...")' in async functions will not trigger error middleware and in fact will not even be caught by any exception handler wrapping the async function. You can't find this info anywhere else.
  • Using domains are a better alternative to catching uncaughtException.
  • Domains are in the process of being deprecated. What's the alternative API?
  • Was struggling to throw an exception and Express don't catch it. Nice explanation.
  • Here is a npm package do this: npmjs.com/package/express-domain-middleware
  • best answer/solution!
  • The domain module is pending deprecation. So I wouldn't recommend using it.
  • Your example works (after adding var express = require('express');), but unfortunately when I do the same thing in my code it still crashes the process. I've updated the question with sample code.
  • I've updated the answer showing how to capture the error and pass it to express using next().
  • Thank you @250R ! Unfortunately I cannot afford to litter the code logic everywhere with such constructs, so I will go with the solution Matt linked to, in the comments above.
  • Looks like recent node.js uses var errorhandler = require('errorhandler'); app.use(errorhandler());.
  • This method adds so much boilerplate :(