Async error handling

suggest change

Try 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);
});

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents