#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 22 of 50medium

How to Handle Errors in JavaScript?

Understanding try/catch and error types.

What You'll Learn

  • try/catch/finally
  • Error types
  • Custom errors

Try/Catch/Finally

code.jsJavaScript
try {
  const data = JSON.parse(invalidJson);
} catch (error) {
  console.error('Parse error:', error.message);
} finally {
  console.log('Always runs');
}

Error Types

TypeDescription
ErrorGeneric error
SyntaxErrorInvalid syntax
ReferenceErrorInvalid reference
TypeErrorInvalid type
RangeErrorNumber out of range
code.jsJavaScript
new TypeError('Expected string');
new ReferenceError('x is not defined');

Custom Errors

code.jsJavaScript
class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}

function validateEmail(email) {
  if (!email.includes('@')) {
    throw new ValidationError('Invalid email', 'email');
  }
}

try {
  validateEmail('invalid');
} catch (e) {
  if (e instanceof ValidationError) {
    console.log(`${e.field}: ${e.message}`);
  }
}

Async Error Handling

code.jsJavaScript
// Promises
fetch('/api/data')
  .then(res => res.json())
  .catch(err => console.error(err));

// Async/await
async function fetchData() {
  try {
    const res = await fetch('/api/data');
    return await res.json();
  } catch (error) {
    console.error('Fetch failed:', error);
  }
}