对多个 then 方法使用相同的 catch 块

Rya*_*ell 1 error-handling catch-block node.js promise

鉴于:

  • NodeJS v0.10.25
  • 启用所有 Harmony 功能
  • "use strict"

以及以下代码:

   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);
    });
Run Code Online (Sandbox Code Playgroud)

注意多个相同的 catch 块:

.catch(function(err) {
          console.error('DBASE ' + err);
        });
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*oor 5

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

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);
});
Run Code Online (Sandbox Code Playgroud)