Javascript Node.js MySQL 模块 - 抛出错误;// 重新抛出非 MySQL 错误;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45787211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:13:09  来源:igfitidea点击:

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

javascriptmysqlnode.jsserver-side

提问by Null

today I tried node.js mysql snippet from w3schools:

今天我尝试了 w3schools 的 node.js mysql 片段:

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:

我想学习如何处理 mysql 错误,因为我的应用程序需要 mysql。但是在我启动 app.js 文件后,这个错误出现了:

Why can't I throw an error?

为什么我不能抛出错误?

采纳答案by EMX

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

我想学习如何处理 mysql 错误,因为我的应用程序需要 mysql。

MySQLJS Error handling

MySQLJS 错误处理

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

要捕获错误throw,请尝试使用以下代码段:

con.on('error', function(err) {
  console.log("[mysql error]",err);
});

回答by Rizal Amrullah

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);
});