简体   繁体   English

如何在http.ServerResponse对象上调用end()?

[英]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. 请注意注释 - 需要完成http.ServerResponse,以便应用程序最终不会耗尽内存 - 这是一个问题。

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. 'uncaughtException'处理程序无权访问响应对象,因此无法结束响应。 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. 注释的假设是你不应该依赖'uncaughtException'来满足你的所有错误处理需求,因为在很多情况下(比如提到的那个)你没有正确处理错误的范围。

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. 因为你没有捕获Exception,它表明应用程序不知道发生了什么。 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)... 这会轻微打击性能(RPC与进程通信),但这意味着你可以轻松入睡,而小块出错,重启并且一切都很好,因为它们永远不会维持状态(使用Redis)...

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: 如果你真的想在请求中捕获异常然后在请求上调用end(),你必须使用一个具有访问权限的闭包,如下所示:

// 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');
  })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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