[英]Exception handling in promises
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 在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 在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: 在上述情况下,没有运行mysql的实例,我在控制台中得到的输出是:
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. 您没有处理connect
调用中的错误。 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. try
/ catch
将捕获发生的同步错误,但通过回调connect
报告成功/失败。 More in the npm mysql documentation . 有关更多信息,请参见npm mysql文档 。
And, of course, then handle the rejection with a catch
handler at point of use, as trincot pointed out . 而且,当然,再处理与一个拒绝catch
在使用点处理程序,如trincot指出 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.