little_monkey
little_monkey

Reputation: 439

How to make NodeJS carry on even if an error occurs?

I am building a simple login/register app. I am testing the login part. Whenever I input a wrong login, however, the backend (written in NodeJS and Express) crashes and stops.

Previously my code threw an error whenever the SQL returned error like so:

con.query("SELECT * FROM table_name WHERE username=" + usernameGiven, function(er, result) {
    if (er) throw er;
    return result;
} 

This worked but had the issue as told above. So I removed the throw er part and replaced it with console.log(er) but still the nodeJS would stop and further login attempt will throw a CORS error.

So how can I stop it from doing and make it just log it and continue to the next request?

Edit:

I tried try and catch as shown below:

try {
        con.query(sql_query, function(er, result) {
            if (er) {
                console.log(er);
            }
            response.json(result);
        })
    } catch (er) {
        console.log(er);
    }

However this still shows an error:

/home/x/CodeOver/LoginForm/api/node_modules/mysql/lib/protocol/Parser.js:437
      throw err; // Rethrow non-MySQL errors
      ^

TypeError: Cannot read property 'password' of undefined
    at Query.<anonymous> (/home/x/CodeOver/LoginForm/api/api.js:43:37)
    at Query.<anonymous> (/home/x/CodeOver/LoginForm/api/node_modules/mysql/lib/Connection.js:526:10)

Upvotes: 1

Views: 112

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30705

I'd suggest a little refactoring to make the code more robust to this type of failure.

The try .. catch blocks won't actually catch query errors in this situation, though I'll leave them there in case of any other error.

We should also use parameters here when querying. SQL Injection attacks are bad news and using parameters will also make the query less likely to result in a syntax error.

I'd also fail early and throw back a 400 error if our usernameGiven is not present.

Here is the updated code, I hope this helps you!

try {
    if (!usernameGiven) {
        response.status(400).send("Bad Request");
        return;
    }
    let sql_query = "select * from table_name where username = ?";
    con.query(sql_query, [usernameGiven], function(er, result) {
        if (er) {
            console.error("Error occurred:", er);
            response.status(500).send("Internal Server Error")
        } else {
            response.json(result);
        }
    })
} catch (er) {
    console.error("Error occurred:", er);
}

Upvotes: 1

Related Questions