mysqljs / mysql

A pure node.js JavaScript Client implementing the MySQL protocol.
MIT License
18.27k stars 2.52k forks source link

README section on fatal errors is inaccurate #2519

Closed bmaupin closed 2 years ago

bmaupin commented 3 years ago

The README gives this example on fatal errors, which I was trying to use to test generating a fatal error for an issue I'm having:

var connection = require('mysql').createConnection({
  port: 84943, // WRONG PORT
});

connection.connect(function(err) {
  console.log(err.code); // 'ECONNREFUSED'
  console.log(err.fatal); // true
});

connection.query('SELECT 1', function (error, results, fields) {
  console.log(error.code); // 'ECONNREFUSED'
  console.log(error.fatal); // true
});

However the code to log err.code is never reached:

$ node .
internal/validators.js:217
    throw new ERR_SOCKET_BAD_PORT(name, port, allowZero);
    ^

RangeError [ERR_SOCKET_BAD_PORT]: Port should be >= 0 and < 65536. Received 84943.
    at validatePort (internal/validators.js:217:11)
    at lookupAndConnect (net.js:1002:5)
    at Socket.connect (net.js:978:5)
    at Object.connect (net.js:189:17)
    at Connection.connect (node_modules/mysql/lib/Connection.js:76:13)
    at Object.<anonymous> (app.js:7:12)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12) {
  code: 'ERR_SOCKET_BAD_PORT'
}

Not only that, but the error that is thrown does not have err.fatal set. Using this code:

var connection = require('mysql').createConnection({
  port: 84943, // WRONG PORT
});

try {
  connection.connect(function (err) {
    if (err) {
      console.error('error: ' + err.stack);
    }
  });
} catch (err) {
  console.log('err.code=', err.code);
  console.log('err.fatal=', err.fatal);
}

I get this output:

$ node .
err.code= ERR_SOCKET_BAD_PORT
err.fatal=

Maybe it would be better to use a different example? Thanks!

dougwilson commented 3 years ago

It looks like Node.js changed how it handles bad ports like that, which is why the example is not working with the current Node.js . It should still work, so it may just be a bug in the module now and not an issue with the docs.

dougwilson commented 2 years ago

I updated the README to use a commonly blocked port instead of an invalid port, which addresses your main issue. I will also follow up with a fix to forward thrown errors from Node.js connect to the callback as well.