Sometimes constructing a promise there may be an exceptional condition such as database refused the connection or invalid host name parameter for database, for example:
In 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);
}
}
In 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');
});
In the above case there is no instance of mysql running, the output that I get in the console is:
Connected to database
Unhandled Exception connect ECONNREFUSED 127.0.0.1:3306
Which is not as expected, I need to know what is the recommended approach and what I am doing wrong here?
You're not handling errors in the connect
call. See lines with ***
comments:
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');
}
});
};
The try
/ catch
will catch synchronous errors that occur, but connect
reports success/failure via callback. More in the npm mysql documentation .
And, of course, then handle the rejection with a catch
handler at point of use, as trincot pointed out .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.