最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js MySQL module - throw err;Rethrow non-MySQL errors; - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Jan 30, 2020 at 19:13 t.niese 40.9k9 gold badges77 silver badges107 bronze badges asked Aug 20, 2017 at 22:08 NullNull 871 gold badge1 silver badge6 bronze badges 8
  • Well. You wanted to throw an error. You achieved it. What else do you need? – LEQADA Commented Aug 20, 2017 at 22:12
  • @LEQADA Why can't I catch it when I wrap con.connnect() to try-catch? – Null Commented Aug 20, 2017 at 22:22
  • 1 What you said to your application is to throw an error when there is any. And that is what your app is doing. – LEQADA Commented Aug 20, 2017 at 22:23
  • @LEQADA Shouldn't I be able to catch an exception? – Null Commented Aug 20, 2017 at 22:26
  • Try to replace your first if (err) throw err; with this line if (err) console.log("Oops... Something went wrong"); – LEQADA Commented Aug 20, 2017 at 22:32
 |  Show 3 more ments

2 Answers 2

Reset to default 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);
});

change you're database conn like this

  var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'example',
  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);
});

发布评论

评论列表(0)

  1. 暂无评论