0

When MySQL returns an error / exception, my nodejs server crashes.

Here is the code from my backend. I used if else in the query function, then I get the response but my server crashes. With try and catch it still crashes and I don't get any response back.

Rezervacija.create = function (newEmp, result) {
try{
  konekcija.query("INSERT INTO rezervacija set ?", newEmp, function (err, res) {
  
  console.log(res.insertId);
  result(null, res.insertId);

});
}
catch(err){
  result(err, null);
  console.log("Error",err);
}
};

I tried, try and catch, but it doesn't seem to work, maybe im using it wrong? I'm really new to JS and still learning.

The only solution I see is to catch the error so it doesn't crash the server.

Thanks in advance.

2 Answers2

1

I've never used a mysql with node but there is a difference between official example and yours.

connection.query('INSERT INTO posts SET ?', {title: 'test'}, function (error, results, fields) {
  if (error) {
    throw error;
  }
  console.log(results.insertId);
});

For me every time when you are using callback function you have to handle errors first in it and after that when you call your function you have to handle the errors too.

As your example you can try this:

Rezervacija.create = function (newEmp, result) {
    konekcija.query("INSERT INTO rezervacija set ?", newEmp, function (err, res) {
        if (err) {
            throw err;
        }
        
        console.log(res.insertId);
        result(null, res.insertId);
    });
};

P.s. - Because I'm slavic I understand your variables but it will be better if you are using english for names of your variables, functions and etc in your code.

GTsvetanov
  • 1,250
  • 6
  • 16
  • Thanks for your time. I' will keep the variables in english, just thought these few words won't matter. This still doesn't help my case, since I kind of want to bypass the error. Throwing an error resuluts in not getting a response back and still crashing the server. But thank you for your time :) – Dominik Kukovec Dec 29 '20 at 17:10
  • @DominikKukovec any errors which are causing the crash? – GTsvetanov Dec 29 '20 at 17:17
  • I get ER_SIGNAL_EXCEPTION which is the exception caused by MySQL and ERR_HTTP_HEADERS_SENT. – Dominik Kukovec Dec 29 '20 at 17:20
  • @DominikKukovec did you check https://stackoverflow.com/questions/40141332/node-js-mysql-error-handling – GTsvetanov Dec 29 '20 at 17:23
  • I kind of passed through that one, is the conclusion in that thread that I should use async await with it? – Dominik Kukovec Dec 29 '20 at 17:28
0

I kind of solved it the though man's way.

What I did was I commented the line in mysql parser.js where it throws an error, it's on line 437. In your response you still get the error message from the MySQL DB but it doesn't crash the server anymore.

If I get a better answer that will work here, I will definitely use that.

But since this is a project for University, this will work fine :)