CoreUI ONE — 250+ PRO components and 25+ admin templates for React, Angular, Vue, Bootstrap and Next.js, plus Data Grid, Scheduler, 4,300+ PRO icons and the Next.js boilerplate. One license. → See what you get

How to catch an error in JavaScript

Catching errors properly is essential for building robust JavaScript applications that handle failures gracefully without crashing. As the creator of CoreUI, I’ve implemented comprehensive error handling in countless production systems. The most effective solution is to use try-catch blocks to wrap code that might throw errors. This approach allows you to handle exceptions gracefully and provide meaningful feedback to users.

Use try-catch blocks to catch and handle errors in JavaScript.

try {
  const data = JSON.parse('invalid json')
  console.log(data)
} catch (error) {
  console.error('Failed to parse JSON:', error.message)
  // Handle the error gracefully
}

console.log('Application continues running')

The try block contains code that might throw an error. If an error occurs, execution immediately jumps to the catch block, which receives the error object as a parameter. The error object contains properties like message for the error description and stack for the stack trace. After handling the error, the program continues executing normally instead of crashing. This pattern is essential for operations like parsing JSON, network requests, or any code that might fail.

Best Practice Note

This is the same error handling pattern we use in CoreUI components to ensure graceful degradation. Always log errors for debugging but show user-friendly messages to end users. You can also use a finally block after catch to execute cleanup code that should run regardless of success or failure.


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 loop through an array in JavaScript
How to loop through an array in JavaScript

How to get element ID in JavaScript
How to get element ID in JavaScript

How to Get Unique Values from a JavaScript Array
How to Get Unique Values from a JavaScript Array

How to return multiple values from a JavaScript function
How to return multiple values from a JavaScript function