2017-09-10 112 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