1

I have a simple Request/Reply NATS app. The code in subscribe function may fail with error in real app. Can anyone advice me a correct way to response with an Error from my subscribe function? Or maybe explain the correct way of handling errors in NATS Request/Reply messaging.

This is an example code:

const NATS = require('nats');

const nats = NATS.connect();

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

nats.subscribe('help', {queue: 'help'}, (request, replyTo) => {
  console.log('[x] subscribe request: ', request);
  const payload = JSON.parse(request);
  setTimeout(() => {
    // What if my code fails here? Is there a good way to publish an error?
    nats.publish(replyTo, `${payload.name}! I can help!`);
  }, getRandomInt(100, 999));
});

const payload = {
  name: 'Bob'
};
nats.requestOne('help', JSON.stringify(payload), {'max':1}, 1000, (response) => {
  // Is there a good way to handle errors from `subscribe()` here?
  if (response instanceof NATS.NatsError && response.code === NATS.REQ_TIMEOUT) {
    console.log(`Request for help timed out`);
    return;
  }
  console.log(`Got a response for help: ` + response);
});
Peter Gerasimenko
  • 1,906
  • 15
  • 13

1 Answers1

0

You could use something like JSend for all types of answers (success, errors etc.).

See also Standard JSON API response format?

Markus R
  • 541
  • 1
  • 4
  • 6