Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 353
Null Avatar asked Aug 20 '17 22:08

Null


2 Answers

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);
});
like image 141
EMX Avatar answered Nov 10 '22 04:11

EMX


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);
});
like image 34
Rizal Amrullah Avatar answered Nov 10 '22 03:11

Rizal Amrullah