node - 处理db错误而不会崩溃

时间:2016-09-19 20:34:06

标签: node.js

无论数据库的类型如何,我都无法清楚地了解处理数据库错误的最佳方法,而不会导致应用程序崩溃。

e.g connecting with sql

pool.getConnection(function(err, connection) {
  if (err) {
    throw err
  }

  connection.execute('select * ...' , values, function(err, result) {
    if (err) {
     throw err;
   }
}); 

});

在上述两种情况下,我都会抛出导致节点服务器崩溃的错误。 我想注册错误并以最优雅的方式回复请求。任何人都可以指出正确的方向吗?

1 个答案:

答案 0 :(得分:1)

当你抛出错误时,有人需要抓住它们。如果你没有在代码中的任何地方捕获它们,它将导致程序崩溃。

所以基本上你需要做的就是使用try / catch包含对函数的调用,以防你记录它并向请求者返回一个apporopriate响应。

类似的东西:

try {
 pool.getConnection(function(err, connection) {
  if (err) {
    throw err
  }

  connection.execute('select * ...' , values, function(err, result) {
    if (err) {
     throw err;
   }
 }); 
 });
} catch (error) {
  log(error);
  res.status(500).body("failed to get ... " + err).send();
}

我还建议阅读this blog post,对主题有很好的解释

相关问题