Async error handling
suggest changeTry catch
Errors must always be handled. Synchronous code can use try/catch. That does not catch an error thrown later from a callback. Example:
try {
setTimeout(function() {
throw new Error("I'm an uncaught error and will stop the server!");
}, 100);
}
catch (ex) {
console.error("This error is not caught, because it was thrown asynchronously: " + ex);
}
Async errors will only be handled inside the callback function!
Working possibilities
Last-resort process handlers
An uncaughtException handler can synchronously log a fatal error before shutdown. The process may be in an undefined state, so do not resume normal work from this handler:
process.on('uncaughtException', error => {
console.error(error);
process.exitCode = 1;
});
Promises and async functions
The domain module is deprecated. Promise-based APIs propagate asynchronous errors to catch:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function runTask() {
await delay(10);
throw new Error('task failed');
}
runTask().catch(error => {
console.error(error.message);
});
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents