Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 
like image 322
user124114 Avatar asked Apr 30 '12 21:04

user124114


People also ask

What is exception in node JS?

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.

How would you handle errors for async code in node JS?

If we want to handle the error for asynchronous code in Node. js then we can do it in the following two manners. Handle error using callback: A callback function is to perform some operation after the function execution is completed. We can call our callback function after an asynchronous operation is completed.

How do I fix a process out of memory exception in node JS?

This exception can be solved by increasing the default memory allocated to our program to the required memory by using the following command. Parameters: SPACE_REQD: Pass the increased memory space (in Megabytes).

How do you handle operation results with node js?

JavaScript does not have access to the computer's internals. When such operations are to be carried out, JavaScript transfers them to Node. js to handle in the background. Upon completion, they are transferred to the IO callback queue for the event loop to transfer to the call stack for execution.


1 Answers

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.

like image 111
metamatt Avatar answered Oct 17 '22 08:10

metamatt