当NodeJS应用程序发生错误时,如果发生异常,服务器可能会崩溃并停止。
如何防止这种情况,以便服务器永远不会因错误而停止,而是返回错误代码?
-- 编辑
这是一个导致服务器崩溃的方法(表 foo 不存在):
app.get('/articles/list', function(req, res) {
connection.query('select * from foo', function(err, rows, fields) {
if (err) throw err;
res.send(JSON.stringify(rows));
});
});
--最佳解决方案 最后,我找到了最适合我的解决方案: http://rowanmanning.com/posts/node-cluster-and-express/
总而言之,它包括使用服务器集群,并在服务器退出时重新启动服务器
最佳答案
如果您使用express
,则可以使用此
function clientErrorHandler (err, req, res, next) {
if (req.xhr) {
res.status(500).send({ error: 'Something failed!' })
} else {
next(err)
}
}
app.use(clientErrorHandler);
我建议你准备好这个article ,它会为你澄清很多。
JFK,一旦您拥有包含在 try-catch
中的异步内容,请注意异步错误捕获,这是最常见的错误。
另外,避免使用
process.on("uncaughException", () => {....})
这非常糟糕,因为当抛出未捕获的异常时,此时您无法可靠地继续您的程序。让它失败并使用 daemonizer's
重新启动,例如 pm2
、forever
等。
关于node.js - NodeJS : prevent application to crash on error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41166804/