0

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?

2
  • Does store.getRow returns a Promise? Commented Jun 3, 2020 at 15:05
  • @Baboo_ I updated the question with the information you requested. Thanks Chris. Commented Jun 3, 2020 at 15:46

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Wow! Thanks for the exceptional answer. I will try implementing this. Thank you.
Consider accepting an answer if it solves your issue. It helps other developers to find a solution to similar problems and it rewards the dev that took time to answer you ;)
Definitely will do that. Thanks again!
0

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.

3 Comments

Thank you. I just updated the question. Not sure if that changes your answer.
Actually you should have proper way of handle the exception on your application. Please follow this URL github.com/narayansharma91/node_quick_start_with_knex
It contains all the best practice while working with node including exception handling

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.