The1987
The1987

Reputation: 45

How to add error handling to node / express mySQL functions

I am working to improve the error handling in my node/express app, but am slightly lost.

For example here is a route I have that I want to improve:

app.get("/api/max-value", function (req, res) {
    const shop_domain = req.query.shop;
    if (shop) {
        table = 'max_value_table';
        condition = "shop='" + shop + "'";
        store.getRow(table, condition, function (data) {
            return res.json({
                currencySymbol: data[0].currencySymbol,
                currencyDecimal: data[0].currencyDecimal,
                currencyAmount: data[0].currencyAmount,
            })
        });
    }
});

store.getRow is calling this function, but the error handling throws the error and crashes my app.

getRow: function (table, condition, cb) {

var queryString = "SELECT * FROM " + table + " WHERE " + condition + ";";

console.log('mySQL getRow: ', queryString);
connection.query(queryString, function (err, result) {
  if (err) {
    throw err;
  }
  cb(result);
});

},

What I want to add is error handling for the store.getRow function. If the function runs and the condition is not met in the MySQL db return error message / send like a res.send().

Should I amend the if(err) to do something else?

Upvotes: 0

Views: 907

Answers (2)

Baboo
Baboo

Reputation: 4278

You can first refactor your piece of code that retrieve entries to return a Promise. It avoids the callback hell and helps to write cleaner code:

function getEntries(table, condition) {
    return new Promise((resolve, reject) => {
        var queryString = "SELECT * FROM " + table + " WHERE " + condition + ";";

        connection.query(queryString, function (err, result) {
        if (err) {
            reject(err);
        }

        resolve(result);
        });
    });
}

This code performs the same as before but returns a Promise instead of taking a callback as parameter.

Then you can seperate the business logic from the error handling. As you read clean code, this will help your functions 'do one thing':

// Business logic

function getShopMaxValue(req) {
    const shop = req.query.shop;
    if (shop) {
        throw new Error("Shop is not defined");
    }

    const table = 'max_value_table';
    const condition = "shop='" + shop + "'";
    const entries = await store.getEntries(table, condition);
    return formatEntries(entries);
}

function formatEntries(entries) {
    return {
        currencySymbol: entries[0].currencySymbol,
        currencyDecimal: entries[0].currencyDecimal,
        currencyAmount: entries[0].currencyAmount,
    };
}

// Error Handling 

app.get("/api/max-value", async function (req, res) {
    try {
        const maxValue = getShopMaxValue(req);
        return res.json(maxValue);
    }catch(e) {
        return res.send(/* Error. */);
    }
});

This way the code is more readable and more testable.

You can even go further by creating a function like getEntries that specifies the table for you. This way the code that retrieves entries doesn't have to know the architecture of the database and you avoid errors due to mistyped table names.

Upvotes: 1

narayansharma91
narayansharma91

Reputation: 2353

It's all depend upon which method or library you are using to connect with database.

1.Using Error First Callback

con.query("SELECT * FROM customers", function (err, result, fields) {
   if (err) {
     //you will received error over here. and you can handle as per your continent. 
   }
   console.log(result);
});

2. If you are using some library to connect with database (eg. sequelize)(via promise)

Model.findById(123).then(function(result) {
  //result will 
}).catch(err => {
 //you will received error over here. and you can handle as per your continent. 
})

3. Using async/await (ES7)

try {
    const data = await store.getRow(table, condition);
      return res.json({
        currencySymbol: data[0].currencySymbol,
        currencyDecimal: data[0].currencyDecimal,
        currencyAmount: data[0].currencyAmount,
      })
} catch(err => {
 //you will received error over here. and you can handle as per your continent. 
});

I think it will help you to fix the issues.

Upvotes: 0

Related Questions