Deno nuggets: Handle uncaught errors

Mayank C
Tech Tonic

--

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to handle uncaught errors and prevent Deno from exiting?

setTimeout(() => {
// do something
throw new Error("This is an uncaught error");
}, 1000);

Deno exits whenever there is uncaught error:

> deno run app.ts
error: Uncaught Error: This is an uncaught error
throw new Error('This is an uncaught error');
^
at file:///Users/mayankc/Work/source/denoExamples/app.ts:3:9
at Object.action (deno:ext/web/02_timers.js:145:13)
at handleTimerMacrotask (deno:ext/web/02_timers.js:62:12)
>

Solution

Note: The solution works only for uncaught errors, not uncaught rejections

To handle uncaught errors, we need to take two steps:

  • Add an error event handler (addEventListener)
  • Prevent error from propagating further (preventDefault)

The preventDefault web API of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. In Deno, whenever preventDefault is called on an event, the error event stops propagating.

Here is the updated code:

addEventListener("error", (event) => {
console.log("Caught unhandled event:", event.message);
event.preventDefault();
});
setTimeout(() => {
// do something
throw new Error("This is an uncaught error");
}, 1000);

A quick run shows that the error event gets handled cleanly, and Deno quits only when the program finishes:

> deno run app.ts
Caught unhandled event: Uncaught Error: This is an uncaught error
>

Note again: The solution works only for uncaught errors, not uncaught rejections

--

--