为什么NodeJS域文档代码试图终止进程

为什么NodeJS域文档代码试图终止进程

本文介绍了为什么NodeJS域文档代码试图终止进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在官方的NodeJS文档中有一些代码示例,当域中有异常时,进程尝试正常退出(它关闭连接,等待一段时间用于其他请求,然后退出)。

In the official NodeJS documentation there is code example where process tries to exit gracefully when there was exception in domain (it closes connections, waits for some time for other requests and then exits).

但是为什么不发送500错误并继续工作?

But why just not send the 500 error and continue to work?

在我的应用程序中,我想抛出一些预期当用户输入无效时,错误(如FrontEndUserError),并在中间件中捕获这些异常,以向客户端发送漂亮的错误消息。使用域名非常容易实现,但是有没有任何陷阱?

In my application I want to throw some expected Errors (like FrontEndUserError) when user input is not valid, and catch these exceptions somewhere in middleware to send pretty error message to client. With domains it very easy to implement, but are there any pitfalls around this?

app.use (err, req, res, next) ->
  if err instanceof FrontEndUserError
    res.send {error: true, message: err.message}
  else
    log err.trace
    res.send 500


推荐答案

从模块官方文档:

应对投掷错误的最安全的方法是关闭进程...

The safest way to respond to a thrown error is to shut down the process ...

对我来说,这意味着当您的NodeJS应用程序发生错误时,您很遗憾。如果你关心你的应用程序的工作原理,结果对你很重要,那么你最好的办法是杀死这个过程并重新启动它。然而,在最后几毫秒,您可以对其他客户端更好,让他们完成工作,对新客户说抱歉,如果您需要,记录一些事情,然后再杀死进程并重新启动。

To me that means when something thrown an error in your NodeJS application, then you're done unfortunately. If you do care about how your application works and the result is important to you, then your best bet is to kill the process and start it again. However, in that last milliseconds, you can be more nice to other clients, let them finish their work, say sorry to new clients, log couple of things if you want and then kill the process and start it again.

这就是NodeJS域模块的文档示例。

That's what exactly happening in the NodeJS domain module's documentation example.

这篇关于为什么NodeJS域文档代码试图终止进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 05:23