DEV Community

Cover image for 4 Commands to Debug “Silent Errors” in JavaScript

4 Commands to Debug “Silent Errors” in JavaScript

By silent errors here I mean an issue that doesn't produces any visible indication.

Some common examples:

  1. Missing Catch Blocks
  2. Long-Running Promises
  3. Shared State Race Conditions
  4. Erroneous Event Listeners

Let’s understand each error in detail and command to debug them:


#1: Debugging Missing Catch Blocks

These errors occur when you miss attaching .catch() handler to your promise. As a result when the promise is rejected, error isn’t surfaced.

You can debug this error by running your code with unhandled-rejections argument. It forces node to terminate the process on unhandled promise rejections, making the error explicit.

node --unhandled-rejections=strict script.js
Enter fullscreen mode Exit fullscreen mode

#2: Debugging Long-Running Promises

Have you come across a Node.js code that:

  • Never completes
  • Consumes excessive memory over time

If yes, then it’s most likely caused by unresolved promise or infinite loop somewhere.

You can validate the issue by limiting the execution time of the script like done below:

timeout 10s node script.js || echo "Warning: Unresolved promise or infinite loop detected"
Enter fullscreen mode Exit fullscreen mode

#3: Debugging Shared State Race Conditions

Shared State Race Conditions occur when multiple callbacks access shared state simultaneously.

Due to the race condition, the program results in unpredictable outcome causing data inconsistencies without visible symptoms during testing.

But fortunately node actually provides a trace-async-hooks option to identify such execution patterns.

node --trace-async-hooks script.js 2>&1 | grep "asyncId"
Enter fullscreen mode Exit fullscreen mode

#4: Debugging Erroneous Event Listeners

Finally let’s talk about errors within event listeners.

These are caused by unhandled promise rejections within event listener callback. This leads to error never getting propagated to the main execution context.

You can identify these errors by redirecting all node event logs to a grep filter to capture errors emitted during event handling

node -r events script.js 2>&1 | grep "Error"
Enter fullscreen mode Exit fullscreen mode

And That’s it.

Hope you’d find these commands useful while debugging silent errors in JavaScript code.

Also, comment below which silent error annoys you the most?

Top comments (0)