Skip to content

Instantly share code, notes, and snippets.

@gjohnson
Last active December 25, 2018 04:38
Show Gist options
  • Save gjohnson/7566343 to your computer and use it in GitHub Desktop.
Save gjohnson/7566343 to your computer and use it in GitHub Desktop.
AMQP error handling.

Producer

Simple producer, nothing wrong here...

var amqp = require('amqp');

var connection = amqp.createConnection({
  port: 5672, host: 'localhost'
});

connection.on('ready', function () {
  var exchange = connection.exchange('demo.direct', {
    type: 'direct',
    durable: true
  });

  exchange.on('open', function () {
    exchange.publish('request.key', {
      hello: 'world'
    });
  });
});

Consumer

However, our consumer attempts to use a function that is not defined, onmessage(). I was thinking this would throw, however node-amqp actually catches it internally and emits an error event on the connection. The gotcha is that node-amqp already has an internal method listening for error events, so we do not get our error bubbled out unless we listen for it on the connection, which you might confuse with an actually network error with rabbit and just exit(1) your process.

I kinda feel like this should throw. Meh?

var amqp = require('amqp');

var connection = amqp.createConnection({
  port: 5672,
  host: 'localhost'
});

connection.on('ready', function () {
  var exchange = connection.exchange('demo.direct', {
    type: 'direct',
    durable: true,
    autoDelete: false
  });

  exchange.on('open', function () {
    var queue = connection.queue('persistor', {
      durable: true,
      autoDelete: false
    });

    queue.on('queueDeclareOk', function () {
      queue.bind('demo.direct', 'request.key');
    });

    queue.on('queueBindOk', function () {
      var options = { ack: true, prefetchCount: 0 };
      queue.subscribe(options, function (msg, headers, info) {
        // call function that is not defined
        onmessage(msg, headers, info);
        queue.shift();
      });
    });
  });
  
  // skip for demo purposes
  // connection.on('error', console.error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment