我有一个简单的请求/回复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);
});