I’m building an infra layer that should run “handlers” periodically.
I’m not the one writing the handlers, their logic can vary.
handlers can run concurrently.
I want the infra to provide isolation, i.e. the infra should make sure that a failure, any application-level failure, in one handler, doesn’t effect other handlers running “in the same time”.
Currently, I surrounded every handler run with try-catch, but as it seems, there are many types of errors that when happen, aren’t being caught in the catch clause and thus crashing the service (cause they are running from a different context).
I assume that at the handler level, one can build the handler in such way all errors are handled, and in many places this is what happen. My problem is that if someone “forgot” to handle the error at the handler level, I, as the infra layer, can’t “catch” those errors for him, thus I can’t enforce isolation and make sure failure in 1 handler doesn’t effect others.
What’s the typescript way of handling such case?
A code illustrating the problem is (assume it’s inside an async function):
try {
await new Promise((resolve, reject) => {
setTimeout(() => {
throw new Error('This error is not caught!');
}, 0)
})
} catch {
console.log("the error never gets here");
}
One solution is find, is to listen on the uncaughtException
event and handle it there, so to add to my service initialization something like:
process.on('uncaughtException', (err) => {
console.error('uncaught exception', err.message);
});
This solves it, but i’m not sure if it’s a good practice and in any way i’m lacking context here, but maybe that’s fine.
Is there a better way of achieving what i want?