我有一个简单的Request/Reply NATS应用。 subscribe
函数中的代码可能会在真实应用程序中失败并显示错误。任何人都可以通过我subscribe
函数的错误向我建议正确的方法吗?或者也许解释在NATS请求/回复消息中处理错误的正确方法。
这是一个示例代码:
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);
});