Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

404 response code from Consul leads to unhandled exception #7

Open
ScavengerSpb opened this issue Dec 30, 2021 · 1 comment
Open

404 response code from Consul leads to unhandled exception #7

ScavengerSpb opened this issue Dec 30, 2021 · 1 comment

Comments

@ScavengerSpb
Copy link

Disclaimer: The issue occurred during debugging so it's unlikely to happen in wildlife.

Due to some reason the leader key was deleted so consul returned 404 error code for which consul library (0.40.0) has special handling. This resulted in undefined being pushed to callback as the call result of client.kv.get method. Console output with debug messages printed to console:

Read key .../leader result:  undefined
...\node_modules\consul\lib\kv.js:56
    if (res && res.statusCode === 404) return callback(undefined, undefined, res);
                                              ^
TypeError: Cannot read properties of undefined (reading 'ModifyIndex')
    at ...\node_modules\exp-leader-election\index.js:55:23
    at Consul.<anonymous> (...\node_modules\consul\lib\kv.js:56:47)
    at next (...\node_modules\papi\lib\client.js:313:25)

It seems when key to read is not found Consul library returns result as undefined to indicate call succeeded but key was not found. It's expected situation so error is not provided as well. Handling of the call result in consul package:

  this.consul._get(req, function(err, res) {
    if (res && res.statusCode === 404) return callback(undefined, undefined, res);
    if (err) return callback(err, undefined, res);
    if (opts.raw) return callback(null, res.body, res);

Callback passed to client.kv.get does not check result for null/undefined so this results in attempt to access property of undefined:

    client.kv.get(waitCmd, (err, res) => {
      if (handleError(err)) return;
      opts.debug("Read key", opts.key, "result: ", res);
      waitIndex = res.ModifyIndex;  <--- Exception is thrown here
      if (!res.Session) {
@ScavengerSpb
Copy link
Author

Code to reproduce this issue:

const Consul = require('consul');
const leaderElection = require('exp-leader-election');

const config = {
    debug: console.log,
    key: 'test/leader',
    consul: {
        host: 'localhost',
        port: '8500'
    }
};

leaderElection(config).on('gainedLeadership', () => {
    setTimeout(() => {
        Consul(config.consul).kv.del(config.key, () => {});
    }, 100);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant