Node.js MySQL Error Handling

后端 未结 6 1782
遇见更好的自我
遇见更好的自我 2020-12-08 22:30

I\'ve read several examples for using mysql in node.js and I have questions about the error handling.

Most examples do error handling like this (perhaps for brevity)

6条回答
  •  北海茫月
    2020-12-08 23:16

    This is a function to return available pool upon successful MySQL connection. So before I proceed with any query, I'll await this function to check whether connection is OK. This will not crash the server even if there's no connection to MySQL.

    connect: function ()
        {
            return new Promise((resolve, reject) => {
                let pool = Mysql.createPool({
                    connectionLimit: config.mysql.connectionLimit,
                    host: config.mysql.host,
                    user: config.mysql.user,
                    password: config.mysql.password,
                    database: config.mysql.database
                });
    
                pool.getConnection((err, con) =>
                {
                    try
                    {
                        if (con)
                        {
                            con.release();
                            resolve({"status":"success", "message":"MySQL connected.", "con":pool});
                        }
                    }
                    catch (err)
                    {
                        reject({"status":"failed", "error":`MySQL error. ${err}`});
                    }
                    resolve({"status":"failed", "error":"Error connecting to MySQL."});
                });
            });
        }
    

    MySQL package used: https://www.npmjs.com/package/mysql

    Native Promise async/await ES2017

提交回复
热议问题