Reputation: 149
In nodejs, we can handle exceptions like this:
process.on('uncaughtException', (err, origin) => {
fs.writeSync(
process.stderr.fd,
`Caught exception: ${err}\n` +
`Exception origin: ${origin}`
);
});
setTimeout(() => {
console.log('This will still run.');
}, 500);
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');
What is the alternative for deno? I know there is window.onunload, but it doesn't handle errors
Upvotes: 5
Views: 3498
Reputation: 1056
It's a design choice (a central one actually) for Deno to always die on uncaught exceptions. You can not place a global handler for your errors, since sometimes your exceptions might be non recoverable and may cause side effects that change the overall state of your application, in summary, unhandled exception handlers mean problems. Global handling of exceptions it's being discouraged by NodeJS as of now so please don't rely on this kind of code in the future in that platform either.
That being said, how to handle rejections? try
/catch
/finally
for sync code. .then
/.catch
/.finally
for async code.
EDIT: An interesting resource you can use is the unhandledRejection
event, it's an event meant to be used to realize a cleanup of sorts, meaning to close open connections, free up resources, close files, etc. This won't stop the exception from terminating the program, but will give you space to prevent secondary effects on the program termination.
https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event
Upvotes: 5