node.js - 对多个 then 方法使用相同的 catch block

标签 node.js error-handling promise catch-block

给定:

  • NodeJS v0.10.25
  • 已启用所有 Harmony 功能
  • “使用严格”

以及以下代码:

   db.connect({
      host: DB_HOST,
      port: DB_PORT
    }).then(function(dbConn) {
      console.log('DBASE connected to ' + DB_HOST + ':' + DB_PORT);
      db.dbList().run(dbConn).then(function(result) {
        if (result.indexOf(SCRIPT_NAME) == -1) throw new Error('unable to locate database ' + SCRIPT_NAME);
        dbConn.use(SCRIPT_NAME);
        console.log('DBASE bound to ' + SCRIPT_NAME + ' on ' + DB_HOST + ':' + DB_PORT);
        db.tableList().run(dbConn)
          .then(function(result) {
            if (!result) throw new Error(SCRIPT_NAME + ' unable to enumerate tables');
            if (!result.length) throw new Error(SCRIPT_NAME + ' has no tables');
            console.log('DBASE ' + DB_HOST + ':' + DB_PORT + '/' + SCRIPT_NAME + ' has ' + result.length + ' table' + ((result.length > 1) ? 's' : ''));
          }).catch(function(err) {
            console.error('DBASE ' + err);
          });
      }).catch(function(err) {
        console.error('DBASE ' + err);
      });
    }).catch(function(err) {
      console.error('DBASE ' + err);
    });

注意多个相同的 catch block :

.catch(function(err) {
          console.error('DBASE ' + err);
        });

是否有推荐/接受/事实上的方法来跨多个级别的控制结构重用该异常处理程序?

最佳答案

错误会冒泡直到被捕获,因此您不需要多次捕获,并且可以通过链接 promise 而不是嵌套它们来使代码更具可读性:

db.connect({
  host: DB_HOST,
  port: DB_PORT
}).then(function(dbConn) {
  console.log('DBASE connected to ' + DB_HOST + ':' + DB_PORT);
  // it's important to return if you have a promise so the chain doesn't break
  return db.dbList().run(dbConn);
}).then(function(result) {
  if (result.indexOf(SCRIPT_NAME) == -1) throw new Error('unable to locate database ' + SCRIPT_NAME);
  dbConn.use(SCRIPT_NAME);
  console.log('DBASE bound to ' + SCRIPT_NAME + ' on ' + DB_HOST + ':' + DB_PORT);
  return db.tableList().run(dbConn);
}).then(function(result) {
  if (!result) throw new Error(SCRIPT_NAME + ' unable to enumerate tables');
  if (!result.length) throw new Error(SCRIPT_NAME + ' has no tables');
  console.log('DBASE ' + DB_HOST + ':' + DB_PORT + '/' + SCRIPT_NAME + ' has ' + result.length + ' table' + ((result.length > 1) ? 's' : ''));
}).catch(function(err) {
  console.error('DBASE ' + err);
});

关于node.js - 对多个 then 方法使用相同的 catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34795381/

相关文章:

javascript - 如何获取分配给 JSON 数组中相同键的重复值的计数 - JavaScript/NodeJS

JSON 一次多个查询

javascript - 如何处理从父 Promise 链返回的 Promise 以及各种可能的结果

JavaScript promise 、解决、拒绝

node.js - 在 MongoDB 中查找不符合条件的记录

javascript - 多人倒计时器

node.js - 使用 FileInterceptor 上传文件时如何在 NestJs 中返回自定义状态代码?

asp.net - 如何防止 ASP.NET 记录身份验证失败?

c# - 如何使用 C# 恢复 Irony Parser 中的解析错误?

c# - C# 任务的 Angular 对应项