Sobes.tech
Middle

What error handling methods exist in JavaScript?

sobes.tech AI

Answer from AI

In JavaScript, there are several ways to handle errors:

  1. try...catch — the classic way to handle exceptions. Code that might throw an error is placed inside the try block, and error handling is done in the catch block.
try {
  // code that might throw an error
  let result = riskyOperation();
} catch (error) {
  console.error('An error occurred:', error);
}
  1. Error handling in promises — using .catch() methods or the second argument of .then().
fetch('/api/data')
  .then(response => response.json())
  .catch(error => console.error('Request error:', error));
  1. async/await with try...catch — for asynchronous code, it's convenient to use try...catch inside async functions.
async function fetchData() {
  try {
    const response = await fetch('/api/data');
    const data = await response.json();
  } catch (error) {
    console.error('Error loading data:', error);
  }
}
  1. window.onerror and window.addEventListener('error') — global error handling in the browser.

  2. Promise rejection handlers — handling unhandled promise rejections via window.onunhandledrejection.

The choice of method depends on the context and the type of code (synchronous or asynchronous).

What error handling methods exist in JavaScript… - sobes.tech