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