How to rethrow an error in JavaScript

Rethrowing errors allows you to handle errors partially at one level while still propagating them to higher-level handlers in JavaScript. As the creator of CoreUI with over 25 years of development experience, I’ve built multi-layered error handling systems in enterprise applications. The most effective solution is to use throw within a catch block to rethrow the caught error after logging or processing. This approach enables error handling at multiple levels while preserving the original error information.

Use throw within a catch block to rethrow errors after handling.

async function fetchUserData(userId) {
  try {
    const response = await fetch(`/api/users/${userId}`)
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    return await response.json()
  } catch (error) {
    console.error('Failed to fetch user data:', error.message)
    throw error
  }
}

try {
  const user = await fetchUserData(123)
  console.log(user)
} catch (error) {
  console.error('Application error:', error)
  // Show user-friendly message
}

The inner catch block logs the error for debugging purposes, then rethrows it using throw error. This allows the outer catch block to handle the error at a higher level, perhaps showing a user-friendly message or implementing retry logic. Rethrowing preserves the original error stack trace, making debugging easier. You can also throw a new error with additional context while preserving the original error as the cause.

Best Practice Note

This is the same error rethrowing pattern we use in CoreUI to log errors at component level while allowing application-level error handlers to respond appropriately. When rethrowing, consider wrapping the error in a custom error with additional context while preserving the original error in a cause property for complete debugging information.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Hide Scrollbar with CSS
How to Hide Scrollbar with CSS

How to Open All Links in New Tab Using JavaScript
How to Open All Links in New Tab Using JavaScript

Understanding the Difference Between NPX and NPM
Understanding the Difference Between NPX and NPM

What is the difference between typeof and instanceof in JavaScript
What is the difference between typeof and instanceof in JavaScript

Answers by CoreUI Core Team