1
有时候构建一个承诺处理可能存在的异常情况,如数据库拒绝了数据库的连接或无效的主机名参数,例如:异常的承诺
在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
这是不是预期的,我需要知道什么是推荐的方法,我在这里做错了什么?
为什么我的代码在'then'块里呢? – CodeYogi
@ codeyogi导致它在连接之前解决。连接是异步的... –
哦,明白了。当'try/catch'运行时没有错误,但由于'connect'的异步特性,稍后会抛出一个错误。 – CodeYogi