Node.js MySQL module - throw err; // Rethrow non-MySQL errors;
Asked Answered
E

2

6

today I tried node.js mysql snippet from w3schools:

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "roots", // WRONG USER
  password: ""
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  /*Create a database named "mydb":*/
  con.query("CREATE DATABASE mydb", function (err, result) {
    if (err) throw err;
    console.log("Database created");
  });
});

I wanted to learn how to handle mysql errors, because my app require mysql. But after I started app.js file this error showed up:

Why can't I throw an error?

Embay answered 20/8, 2017 at 22:8 Comment(8)
Well. You wanted to throw an error. You achieved it. What else do you need?Steffi
@Steffi Why can't I catch it when I wrap con.connnect() to try-catch?Embay
What you said to your application is to throw an error when there is any. And that is what your app is doing.Steffi
@Steffi Shouldn't I be able to catch an exception?Embay
Try to replace your first if (err) throw err; with this line if (err) console.log("Oops... Something went wrong");Steffi
The user you are using to connect doesn't have permissions to access your target database.Disparage
Did you manage to handle errors with my suggestion?Journalese
My doubt also, Why throwing the error is not caught in the catch scope? When making throws error will be caught in catch, but here it is not behaving as expected.Memling
J
5

I wanted to learn how to handle mysql errors, because my app require mysql.

MySQLJS Error handling

To catch the errors you throw, try with the following snippet :

con.on('error', function(err) {
  console.log("[mysql error]",err);
});
Journalese answered 20/8, 2017 at 23:33 Comment(0)
E
2

change you're database conn like this

  var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret',
  database : 'secret'

});

connection.connect(function(err) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }

  console.log('connected as id ' + connection.threadId);
});
Earthlight answered 30/1, 2020 at 19:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.