We are using seneca.js to put messages into a queue in our Node app. We promisified the act
call, and wrapped all the seneca use in a service we called MessageBus. So now, MessageBus.publish uses Seneca to put the call on a queue and wait for a response:
MessageBus.publish({ ... })
.then(result => doSomething(result))
.catch(error => handleError(error));
Here's the relevant part of the service that we wrote:
function MessageBus() {
//initialization
seneca.use('seneca-amqp-transport'); //instruct seneca to use a transport
seneca.client({});
seneca.listen({});
const act = function(message, cb) {
seneca.act(message, function(err, response) {
if (err) {
console.error(err);
cb(err);
} else {
cb(null, response);
}
});
};
const promisified = Promise.promisify(act, { context: seneca });
return {
publish: promisified,
};
}
module.exports = MessageBus();
On every call, we needed to add the catch
to handle errors. That worked pretty well, but had a lot of repeated code.
Now, we're using async/await
, and I'd like to handle the errors all in one spot and not need to wrap every call in a try/catch
block. My attempts, though, didn't work.
What I added was a function that called the promisified
function and caught the errors. Then publish
exported that function instead. It half worked, but in the act
function, cb
was not defined. No matter what I tried, cb
was never defined and never called.
I know it looks like errors are handled in the seneca.act
, but the express app will still crash if an error occurs and the MessageBus.publish
isn't wrapped in a try/catch
block.
My goal was to have something along the lines of Wes Bos's solution in this catchErrors
function. I'd love to not have to wrap every MessageBus.publish
call in a try/catch
block, but instead write that code in one spot and have all the errors handled there.