Skip to main content

Error Handling in JavaScript

Level: Beginner

ℹ️ What You'll Learn
  • What Error Handling in JavaScript means in JavaScript
  • Why this topic matters in real web pages
  • How to use it with School Management System examples
  • Common beginner mistakes to avoid
  • How to explain this topic in interviews

Why This Matters

Error Handling in JavaScript is part of the practical frontend foundation. You will use it when building forms, tables, dashboards, reports, and API-connected screens for ASP.NET Core or full-stack projects.

Handle errors without crashing the application.

The Problem

Beginners often copy JavaScript code without understanding what each line does. In a real School Management System, that leads to pages that are hard to maintain, hard to debug, or confusing for users. This lesson focuses on understanding the pattern first, then applying it in small practical examples.

Try/Catch Block

async function getStudent(id) {
try {
const response = await fetch(`/api/students/${id}`);
const student = await response.json();
console.log(student);
} catch (error) {
console.error('Error:', error);
}
}

Flow:

  • try — Code that might fail
  • catch — Runs if error occurs
  • finally — Always runs (optional)

Check Response Status

async function safeRequest(url) {
try {
const response = await fetch(url);

// Check if response ok (200-299)
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}

const data = await response.json();
return data;
} catch (error) {
console.error('Request failed:', error);
return null;
}
}

API Error Response

async function registerStudent(studentData) {
try {
const response = await fetch('/api/students', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(studentData)
});

if (!response.ok) {
// Server returned error (400, 500, etc)
const error = await response.json();
throw new Error(error.message || 'Registration failed');
}

const result = await response.json();
return result;
} catch (error) {
console.error('Registration error:', error.message);
alert('Error: ' + error.message);
}
}

Different Error Types

async function handleErrors() {
try {
const response = await fetch('/api/students');
const data = await response.json();
return data;
} catch (error) {
if (error instanceof TypeError) {
// Network error (no internet, server down)
console.error('Network error:', error);
alert('No internet connection');
} else if (error instanceof SyntaxError) {
// Invalid JSON
console.error('Invalid JSON:', error);
alert('Server returned invalid data');
} else {
// Other errors
console.error('Error:', error);
alert('Error: ' + error.message);
}
}
}

Finally Block

async function fetchWithLoading(url) {
const loader = document.getElementById('loader');

try {
loader.style.display = 'block';
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
alert('Failed to load data');
} finally {
// Always hide loader
loader.style.display = 'none';
}
}

Real SMS Example: Complete Error Handling

async function loadStudents() {
const loader = document.getElementById('loader');
const errorDiv = document.getElementById('error');

try {
loader.style.display = 'block';
errorDiv.style.display = 'none';

const response = await fetch('/api/students');

if (!response.ok) {
throw new Error(`Server error: ${response.status}`);
}

const students = await response.json();

// Display students
const tableBody = document.querySelector('tbody');
tableBody.innerHTML = '';

students.forEach(student => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${student.rollNumber}</td>
<td>${student.name}</td>
<td>${student.className}</td>
`;
tableBody.appendChild(row);
});

document.getElementById('studentCount').textContent = students.length;

} catch (error) {
// Show error message
errorDiv.style.display = 'block';
errorDiv.textContent = 'Error loading students: ' + error.message;
console.error('Error:', error);
} finally {
// Hide loader
loader.style.display = 'none';
}
}

async function registerStudent(studentData) {
const submitBtn = document.querySelector('button[type="submit"]');
const errorDiv = document.getElementById('formError');

try {
submitBtn.disabled = true;
submitBtn.textContent = 'Registering...';
errorDiv.style.display = 'none';

const response = await fetch('/api/students', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(studentData)
});

if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Registration failed');
}

const result = await response.json();
alert(`Student ${result.name} registered successfully!`);
location.reload();

} catch (error) {
// Show error
errorDiv.style.display = 'block';
errorDiv.textContent = 'Error: ' + error.message;
console.error('Error:', error);
} finally {
// Restore button
submitBtn.disabled = false;
submitBtn.textContent = 'Register Student';
}
}

Validation Error Messages

function validateAndRegister(studentData) {
const errors = [];

if (!studentData.name) {
errors.push('Name is required');
}

if (!studentData.email || !studentData.email.includes('@')) {
errors.push('Valid email is required');
}

if (!studentData.className) {
errors.push('Class is required');
}

if (errors.length > 0) {
const errorMessage = errors.join('\n');
alert('Validation errors:\n' + errorMessage);
return false;
}

// Validation passed
registerStudent(studentData);
}

Custom Error Messages

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

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

try {
validateEmail('ravi');
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation failed:', error.message);
}
}

Key Takeaways

  • Always use try/catch for async operations
  • Check response.ok before parsing
  • Show meaningful error messages to users
  • Use finally for cleanup
  • Handle different error types
  • Next: SMS complete example
💡 Backend Developer Tip

Good error messages make debugging easier. Log errors with context. Include which API call failed and what data was sent.

⚠️ Error Handling Mistakes
  1. Silent failures — Catch error but don't show it
  2. Generic messages — User doesn't know what failed
  3. Not checking response.ok — Parse error on 404
  4. Forgetting finally — Resources leak
  5. Not logging errors — Can't debug issues
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on Error Handling. Try these prompts:

  • "Why check response.ok?"
  • "When use try/catch/finally?"
  • "How do you show errors to users?"
  • "Quiz me on error handling"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Quick Definitions

  • Error Handling in JavaScript - The main concept explained in this lesson.
  • Selector/element/data - The page item or value you work with while applying this concept.
  • Real project usage - How this appears in forms, tables, dashboards, or API-connected pages.

Common Mistakes

  • Copying code without understanding what each line does
  • Forgetting to test with real School Management System data
  • Ignoring mobile screens and accessibility
  • Mixing structure, styling, and behavior in a confusing way
  • Not checking browser DevTools when something does not work

Practice Task

Create a small School Management System example using Error Handling in JavaScript. Keep it simple first, then improve it step by step.

Suggested practice:

  1. Build a small student-related screen or component.
  2. Use clear names for elements, classes, variables, or functions.
  3. Test one success case and one failure case.
  4. Explain the code in your own words.
  5. Rebuild it once without looking at the article.

Quick Revision

QuestionAnswer
What is the main idea?Understand and apply Error Handling in JavaScript in a real page.
Where is it used?Student forms, reports, dashboards, and admin screens.
What should beginners focus on?Clear structure, small examples, and repeated practice.
What is the best debugging habit?Inspect the page in browser DevTools and test one change at a time.
🎯 How would you explain Error Handling in JavaScript in an interview?

Error Handling in JavaScript is a practical JavaScript concept used to build clear, maintainable web pages. I would explain what problem it solves, show a small example, and mention one common mistake beginners should avoid.

🎯 Where is this used in a real project?

It is used in screens like student registration, attendance entry, marks reports, dashboards, and API-connected admin pages.

Next Article

Modern JavaScript Essentials ->

nexcoding.in