2017-09-10 51 views
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 

这是不是预期的,我需要知道什么是推荐的方法,我在这里做错了什么?

回答

2

你没有处理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 documentation

而且,当然,然后处理拒绝catch处理程序在使用点,作为trincot pointed out

+0

为什么我的代码在'then'块里呢? – CodeYogi

+2

@ codeyogi导致它在连接之前解决。连接是异步的... –

+2

哦,明白了。当'try/catch'运行时没有错误,但由于'connect'的异步特性,稍后会抛出一个错误。 – CodeYogi