< / >
Published on

Error Handling

Table of Contents

Error handling in JavaScript is crucial for managing unexpected issues that may arise during the execution of code. This involves using try-catch blocks to catch errors, understanding Error objects, and dealing with errors in asynchronous code.

Try-Catch Blocks

A try-catch block is a JavaScript construct used to handle errors gracefully. Code that might throw an error is placed inside the try block, and if an error occurs, it's caught and handled in the catch block.

Example:

try {
  // Code that might throw an error
} catch (error) {
  // Handling the error
}

try {
  // Code that might throw an error
  const result = someUndefinedVariable / 0
} catch (error) {
  // Handling the error
  console.error('An error occurred:', error.message)
}

Error objects

In JavaScript, errors are represented by objects. These objects provide valuable information about the error, such as its type, message, and stack trace. Common error types include SyntaxError, ReferenceError, TypeError, etc.

Properties of Error Objects

  • name: The name of the error (e.g., ReferenceError).
  • message: A human-readable description of the error.
  • stack: A stack trace, indicating the sequence of function calls that led to the error.

Example:

try {
  // Code that might throw an error
  throw new Error('Custom error message')
} catch (error) {
  // Handling the error
  console.error('An error occurred:', error.name, '-', error.message)
  console.error('Stack trace:', error.stack)
}

Handling asynchronous errors

Handling errors in asynchronous code, such as promises and asynchronous functions, requires special attention. Errors occurring inside asynchronous operations are not caught by surrounding try-catch blocks. Instead, they are captured using the .catch() method for promises or by using async/await syntax.

Example with Promises:

someAsyncFunction()
  .then((result) => {
    // Handle successful result
  })
  .catch((error) => {
    // Handle error
    console.error('An error occurred:', error.message)
  })

Example with Async/Await:

async function fetchData() {
  try {
    const data = await fetch('https://api.example.com/data')
    const jsonData = await data.json()
    // Handle successful data retrieval
  } catch (error) {
    // Handle error
    console.error('An error occurred:', error.message)
  }
}