ItsJay
ItsJay

Reputation: 198

try/catch block can't stop ER_DUP_ENTRY error from crashing my appliction

Im adding a duplicate to a mysql table and I want to handle elicited ER_DUP_ENTRY error comming back with a Try/Catch block but its just crashing anyway , is there any possible way to handle error and stop application from crashing using a try/catch block?

async function init() {
    try {
      connection.query(
        'SOME INSERT QUERY',
        (err, result, feilds) => {
          if (err) throw err
          console.log(result);
        }
      );
    } catch (e) {
      console.log(e);
    }
  }

init(); 

Upvotes: 1

Views: 533

Answers (2)

Always Learning
Always Learning

Reputation: 5591

The problem is that connection.query returns undefined right away. Your catch is not involved because the call ends before the work is done and will call your callback function later. An exception that occurs during your callback is too late. You try/catch block has already completed.

You can use promisify to wait on it like this though:

const util = require("util");
function init() {
  const queryPromise = util.promisify(connection.query);
  return queryPromise('SOME INSERT QUERY')
    .catch(e => {
      console.log("It failed", e);
    });
  }

init().then(result => {
  if (result) console.log("It worked", result);
  else console.log("Aww, it didn't work");
}); 

Upvotes: 1

eol
eol

Reputation: 24565

The node mysql-library does not support promises out of the box, which means query does not return a promise which you can await. So you can either wrap the query function in a promise yourself:

async function init() {
    try {
        const duplicateResult = await new Promise((resolve, reject) => {
                connection.query(
                    'SOME INSERT QUERY',
                    (err, result, fields) => {
                    if (err) {
                        return reject(err);
                    }
                    resolve(result);
                });
            });

    } catch (e) {
        console.log(e);
    }
}

or use util.promisify as Always Learning posted alternatively.

Upvotes: 1

Related Questions