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 with over 25 years of development experience, 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.



