start learning
Image 1
41414

Javascript error handling

Handling errors in JavaScript is crucial for building robust and reliable applications.

Below are best practices for error handling in JavaScript, explained step by step with real examples:

Use try-catch Blocks

try {
  // Code that might throw an exception
  let result = someFunction();
  console.log(result);
} catch (error) {
  // Handle the exception
  console.error('An error occurred:', error.message);
}

Use finally Block (optional)

try {
  // Code that might throw an exception
  let result = someFunction();
  console.log(result);
} catch (error) {
  // Handle the exception
  console.error('An error occurred:', error.message);
} finally {
  // Code that always executes, whether there was an exception or not
  cleanupResources();
}

Use throw to Create Custom Errors

function divide(a, b) {
  if (b === 0) {
    throw new Error('Cannot divide by zero');
  }
  return a / b;
}

try {
  let result = divide(10, 0);
  console.log(result);
} catch (error) {
  console.error('An error occurred:', error.message);
}

Handle Asynchronous Errors

async function fetchData() {
  try {
    // Asynchronous code that might throw an error
    let response = await fetch('https://example.com/data');
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error.message);
  }
}

Use Error Objects Wisely

try {
  // Some code that might throw an exception
  throw new Error('Something went wrong');
} catch (error) {
  console.error('Error name:', error.name);
  console.error('Error message:', error.message);
  console.error('Stack trace:', error.stack);
}

Logging Errors

try {
  // Some code that might throw an exception
  throw new Error('Something went wrong');
} catch (error) {
  console.error('An error occurred:', error);
  // Log to a centralized logging service
  // logErrorToService(error);
}

Global Error Handling

window.onerror = function (message, source, lineno, colno, error) {
  console.error('Global error:', message, source, lineno, colno, error);
  // Log to a centralized logging service
  // logErrorToService(error);
};

These best practices help you handle errors effectively in JavaScript. Adjust your error-handling strategy based on the requirements of your application.

×