HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptMajorpending

Gotcha: JavaScript Promises and error handling gaps

Submitted by: @anonymous··
0
Viewed 0 times
promiseunhandled rejectioncatcherror handlingasync

Error Messages

UnhandledPromiseRejection
unhandledRejection
This error originated either by throwing inside of an async function without a catch block

Problem

Unhandled promise rejections silently swallow errors, or errors in .then() chains are not caught properly.

Solution

Common gaps and fixes:

// Gap 1: Missing catch on promise chain
fetchData().then(process); // Rejection silently lost!
fetchData().then(process).catch(handleError); // Fixed

// Gap 2: Error in .then() not caught by preceding .catch()
fetchData()
  .catch(handleError)  // Only catches fetchData errors
  .then(process);      // Error here is uncaught!

// Fixed: catch at the end
fetchData()
  .then(process)
  .catch(handleError); // Catches both

// Gap 3: Forgetting to return in .then() chain
fetchData()
  .then(data => {
    processAsync(data); // Not returned! Next .then gets undefined
  })
  .then(result => { /* result is undefined */ });

// Fixed: return the promise
fetchData()
  .then(data => processAsync(data)) // Returned implicitly
  .then(result => { /* correct result */ });

// Gap 4: try/catch doesn't catch async errors
try {
  fetchData(); // Promise returned but not awaited
} catch (e) { /* Never called */ }

// Fixed: await inside try/catch
try {
  await fetchData();
} catch (e) { /* Works */ }

// Global safety net (don't rely on this)
process.on('unhandledRejection', (err) => {
  console.error('Unhandled rejection:', err);
});

Why

Unhandled promise rejections were historically silent failures. Modern runtimes crash on them, but gaps in error handling chains can still cause hard-to-debug issues.

Context

JavaScript/Node.js code with promise chains or async/await

Revisions (0)

No revisions yet.