诺言中的例外处理



有时构建诺言可能会有一个特殊条件,例如数据库拒绝了数据库的连接或无效的主机名参数,例如:

在db.js

const mysql = require('mysql');
module.exports.connect = (options) => {
  return new Promise((resolve, reject) => {
    try {
      const connection = mysql.createConnection(getDBConfig());
      connection.connect();
      resolve(connection);
    } catch (err) {
      throw new Error('Error connecting database');
    }
  });
};
function getDBConfig() {
  const isProd = process.env.NODE_ENV === 'production';
  const config = {
    debug: !isProd,
    host: 'localhost',
    user: 'root',
    database: 'xxx'
  };
  if (isProd) {
    return Object.assign({
      password: 'root'
    }, config);
  } else {
    return Object.assign({
      password: 'xxx'
    }, config);
  }
}

在app.js

'use strict';
const database = require('./db');
const server = require('./server');
// log unhandled execpetions
process.on('uncaughtException', (err) => {
  console.error('Unhandled Exception', err.message);
});
process.on('uncaughtRejection', (err, promise) => {
  console.error('Unhandled Rejection', err);
});
database.connect({
})
.then((connection) => {
  console.log('Connected to database');
});

在上述情况下,没有运行mySQL的实例,我在控制台中获得的输出是:

Connected to database
Unhandled Exception connect ECONNREFUSED 127.0.0.1:3306

哪些不是预期的,我需要知道建议的方法是什么,我在这里做错了什么?

您没有处理connect调用中的错误。请参阅***注释的行:

module.exports.connect = (options) => {
  return new Promise((resolve, reject) => {
    try {
      const connection = mysql.createConnection(getDBConfig());
      connection.connect(err => {                         // ***
        if (err) {                                        // ***
          reject(new Error('Error connecting database')); // ***
        } else {                                          // ***
          resolve(connection);                            // ***
        }                                                 // ***
      });                                                 // ***
    } catch (err) {
      throw new Error('Error connecting database');
    }
  });
};

try/catch将捕获发生的同步错误,但是connect通过回调报告了成功/故障。NPM MySQL文档中的更多内容。

,当然,然后 hange 在使用点上使用catch处理程序的拒绝,如Trincot所指出的。

最新更新