简体   繁体   中英

How to call end() on the http.ServerResponse Object?

I found the accepted answer in this question to answer an error handling question I had.

Note the comment though - a http.ServerResponse needs to be finished so that the application doesn't run out of memory eventually - this is a concern.

How would one implement something like that though? how can the callback function have access to said object?

The 'uncaughtException' handler doesn't have access to the response object, so it can't end the response. The presumed point of the comment is that you shouldn't rely on 'uncaughtException' for all your error handling needs because in many cases (like the one mentioned) you're not in the right scope to properly handle the error.

As is mentioned in the answer to this post - if you have an un-caught exception your best approach is to let the process die and recover from there - otherwise you have no idea what the current state of the application is.

Because you did not catch the Exception, it suggests that the application does not know what went on. To get around this - you design your application in lots of little chunks rather than in one process.

This takes a slight hit on performance (RPC vs in process communication) but it means you get to sleep easy whilst tiny chunks go wrong, restart and everything is fine because they never maintain state within themselves (use Redis for that)...

If you really want to catch an exception within a request and then call end() on the request you must use a closure with access to the response like so:

// a method that will catch an error and close the response
var runFunctionSafely = function(res, tryFunction){
  try{
    tryFunction();
  }
  catch(error){
    console.log('there was an error, closing the response...');
    console.log(error);
    res.end();
  }
}

app.get('/test', function(req, res, next) {
  runFunctionSafely(res, function(){
    throw new Error('this is a problem');
  })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM