代码之家  ›  专栏  ›  技术社区  ›  Null

节点。js MySQL模块-throw err;/返回非MySQL错误;

  •  5
  • Null  · 技术社区  · 7 年前

    今天我尝试了node。w3schools的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");
      });
    });
    

    为什么我不能抛出错误?

    2 回复  |  直到 5 年前
        1
  •  4
  •   EMX    7 年前

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

    MySQLJS Error handling

    为了抓住你犯下的错误 throw ,请尝试以下代码段:

    con.on('error', function(err) {
      console.log("[mysql error]",err);
    });
    
        2
  •  1
  •   Rizal Amrullah    5 年前

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