Error Handling and Debugging in JavaScript: Find and Fix Errors
Quick Answer: Error handling helps your JavaScript application respond safely when something goes wrong. Use try, catch, and finally to manage exceptions. Use browser developer tools, breakpoints, and console messages to find the actual cause. Good error handling protects users and helps developers diagnose problems.
1. The Problem: What Happens When an Application Fails?
Imagine a hospital appointment system serving 10,000 patients every day.
A patient enters their name and selects an appointment. The application sends those details to a server. But the server may be unavailable, or the submitted data may be incorrect.
What should happen when the appointment request fails?
Consider this simple appointment example without error handling.
Example 1: Booking appointments without error handling
const appointments = [
{ patient: "Priya", time: "10:00 AM" },
{ patient: "Ravi", time: "11:00 AM" },
{ patient: "Lakshmi", time: "12:00 PM" }
];
function bookAppointment(appointment) {
if (!appointment.patient) {
throw new Error("Patient name is required");
}
console.log("Appointment confirmed for " + appointment.patient);
}
appointments.forEach(bookAppointment);
console.log("Appointment processing completed");
Expected output
Appointment confirmed for Priya Appointment confirmed for Ravi Appointment confirmed for Lakshmi Appointment processing completed
This example works for valid data. But one invalid appointment can stop the entire process.
Now imagine the second patient has no name. The thrown error interrupts the remaining statements.
Example 2: One invalid appointment stops execution
const appointments = [
{ patient: "Priya", time: "10:00 AM" },
{ patient: "", time: "11:00 AM" },
{ patient: "Lakshmi", time: "12:00 PM" }
];
function bookAppointment(appointment) {
if (!appointment.patient) {
throw new Error("Patient name is required");
}
console.log("Confirmed: " + appointment.patient);
}
appointments.forEach(bookAppointment);
console.log("All appointments processed");
Expected output
Confirmed: Priya Uncaught Error: Patient name is required
Important: The third appointment is not processed. The final message is not printed. An uncaught exception interrupts normal execution.
What goes wrong?
- Interrupted execution: Later operations may never run.
- Poor user experience: Users may see an unexpected failure.
- Missing information: Developers may not know which operation failed.
- Risky recovery: The application may leave unfinished work.
- Harder support: Teams may struggle to reproduce the problem.
Now think about thousands of appointments. A single failure should not create confusion across the entire application.
The solution: Handle the error safely
Error handling = deciding what an application should do when an operation fails.
JavaScript provides try and catch for this purpose.
Example 3: Handle each appointment separately
const appointments = [
{ patient: "Priya", time: "10:00 AM" },
{ patient: "", time: "11:00 AM" },
{ patient: "Lakshmi", time: "12:00 PM" }
];
function bookAppointment(appointment) {
if (!appointment.patient) {
throw new Error("Patient name is required");
}
console.log("Confirmed: " + appointment.patient);
}
appointments.forEach((appointment) => {
try {
bookAppointment(appointment);
} catch (error) {
console.error(
"Booking failed:",
error.message
);
}
});
console.log("Appointment processing completed");
Expected output
Confirmed: Priya Booking failed: Patient name is required Confirmed: Lakshmi Appointment processing completed
Each appointment is now handled independently. One invalid record does not stop the remaining records.
Without error handling vs with error handling
| Without error handling | With error handling |
|---|---|
| One exception can stop the loop. | Each appointment can be handled separately. |
| The error may remain unhandled. | The application can respond to the error. |
| Recovery is difficult. | Recovery can be planned. |
| Users may see unexpected failures. | Users can receive useful messages. |
Terms to remember
- Error = a problem that occurs while a program runs.
- Exception = an error condition that interrupts normal execution.
- try = the block where risky code runs.
- catch = the block that handles a thrown exception.
- finally = the block that runs after try and catch finish.
- Debugging = finding and fixing the cause of a problem.
2. How JavaScript Error Handling Works
JavaScript uses a predictable flow for synchronous exceptions.
The runtime enters the try block first. If an exception occurs, control moves to catch. The finally block runs afterward.
Animation 1 — JavaScript exception handling flow
The highlighted stages show how an exception moves through try, catch, and finally.
Understand try, catch and finally
Example 4: Using all three blocks
try {
console.log("Checking appointment details");
throw new Error("Appointment service is unavailable");
console.log("This line will not run");
} catch (error) {
console.error("Booking error:", error.message);
} finally {
console.log("Booking attempt finished");
}
Expected output
Checking appointment details Booking error: Appointment service is unavailable Booking attempt finished
- try: Contains the operation that may fail.
- catch: Receives the thrown error object.
- finally: Runs whether the try block succeeds or throws.
Remember: A return statement or another thrown exception inside finally can affect normal control flow. Avoid using finally to return values or hide errors.
3. Types of Errors in JavaScript
JavaScript provides different error types. Each type helps describe a particular problem.
SyntaxError
SyntaxError = an error caused by invalid JavaScript syntax.
Example 5: Invalid JavaScript syntax
const patient = {
name: "Priya"
age: 28
};
The comma is missing after the name property. JavaScript cannot parse this code.
ReferenceError
ReferenceError = an error caused by accessing a variable that cannot be found.
Example 6: Using an undeclared variable
try {
console.log(patientName);
} catch (error) {
console.log(error.name);
console.log(error.message);
}
Expected output
ReferenceError patientName is not defined
TypeError
TypeError = an operation uses a value in an invalid way.
Example 7: Calling a missing method
const patient = {
name: "Ravi"
};
try {
patient.bookAppointment();
} catch (error) {
console.log(error.name);
}
Expected output
TypeError
RangeError
RangeError = a value falls outside the allowed range.
Example 8: Invalid array length
try {
const appointments = new Array(-1);
} catch (error) {
console.log(error.name);
}
Expected output
RangeError
Common JavaScript error types
| Error type | Meaning | Example cause |
|---|---|---|
| SyntaxError | Invalid syntax | Missing comma or bracket |
| ReferenceError | Missing variable reference | Using an undeclared variable |
| TypeError | Invalid operation for a value | Calling a missing method |
| RangeError | Value outside an allowed range | Negative array length |
| URIError | Invalid URI handling | Malformed encoded URI data |
4. Throw Custom Errors for Business Rules
Sometimes built-in errors do not explain your business problem clearly.
A custom error lets you describe that problem in your application's language.
For example, a hospital appointment must have a patient name and a valid appointment time.
Example 9: Create and handle a custom appointment error
class AppointmentError extends Error {
constructor(message, code) {
super(message);
this.name = "AppointmentError";
this.code = code;
}
}
function bookAppointment(patient) {
if (!patient.name) {
throw new AppointmentError(
"Patient name is required",
"PATIENT_NAME_REQUIRED"
);
}
if (!patient.time) {
throw new AppointmentError(
"Appointment time is required",
"APPOINTMENT_TIME_REQUIRED"
);
}
return "Appointment confirmed for " + patient.name;
}
try {
console.log(bookAppointment({
name: "Priya",
time: "10:00 AM"
}));
console.log(bookAppointment({
name: "",
time: "11:00 AM"
}));
} catch (error) {
if (error instanceof AppointmentError) {
console.error(error.code + ": " + error.message);
} else {
console.error("Unexpected error", error);
}
}
Expected output
Appointment confirmed for Priya PATIENT_NAME_REQUIRED: Patient name is required
The custom error contains a readable message and a stable error code. Your application can use that code for controlled responses.
5. Handle Asynchronous Errors with async and await
Modern JavaScript applications often call APIs. An API = a way for applications to exchange data.
These calls may fail because of network problems or server errors. A normal synchronous try/catch cannot catch a later rejected Promise unless you await it inside the try block.
Example 10: Handle a failed asynchronous request
async function loadAppointments() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/invalid-endpoint"
);
if (!response.ok) {
throw new Error(
"Appointment service returned " + response.status
);
}
const appointments = await response.json();
console.log(appointments);
} catch (error) {
console.error("Unable to load appointments:", error.message);
}
}
loadAppointments();
Expected output
Unable to load appointments: Appointment service returned 404
Important: The example checks response.ok. Fetch does not reject its Promise for HTTP error responses such as 404 or 500. You must check the response status yourself.
Handle multiple asynchronous operations
Use Promise.all() when every operation must succeed. It rejects when one of its input Promises rejects.
Example 11: Load patient and appointment data together
async function loadHospitalData() {
try {
const [patients, appointments] = await Promise.all([
fetch("/api/patients").then((response) => {
if (!response.ok) throw new Error("Patients request failed");
return response.json();
}),
fetch("/api/appointments").then((response) => {
if (!response.ok) throw new Error("Appointments request failed");
return response.json();
})
]);
console.log({ patients, appointments });
} catch (error) {
console.error("Hospital data could not be loaded:", error.message);
}
}
This code assumes both API endpoints exist and return JSON. Replace the sample paths with your application's real endpoints.
6. Debugging JavaScript with Browser Developer Tools
Error handling responds to failures. Debugging helps you find why they happened.
Browser developer tools = built-in tools for inspecting and testing web applications.
You can open developer tools in most browsers using F12. Select the Sources panel to inspect JavaScript and set breakpoints.
Animation 2 — A practical debugging investigation
The highlighted investigation stages show a repeatable debugging workflow.
Use console methods
The console helps you inspect values and understand application flow.
Example 12: Useful console methods
const appointment = {
patient: "Priya",
time: "10:00 AM",
confirmed: true
};
console.log("Appointment details", appointment);
console.info("Checking appointment status");
console.warn("Appointment confirmation is pending");
console.error("Sample booking error");
console.table([appointment]);
Use the right console method for each situation:
console.log()prints general information.console.info()prints informational messages.console.warn()highlights possible problems.console.error()reports errors.console.table()displays structured data in a table.
Use breakpoints
A breakpoint = a marker that pauses JavaScript at a selected line.
- Open your browser's developer tools.
- Select the Sources panel.
- Find the JavaScript file you want to inspect.
- Click the line number to add a breakpoint.
- Repeat the action that causes the problem.
- Inspect variables in the Scope panel.
- Use Step Over and Step Into to follow execution.
Use debugger
You can also add the debugger statement directly in your code. The browser pauses there when developer tools are open.
Example 13: Inspect appointment data
function confirmAppointment(appointment) {
const patientName = appointment.patient;
debugger;
if (!patientName) {
throw new Error("Patient name is missing");
}
return "Confirmed for " + patientName;
}
console.log(confirmAppointment({
patient: "Lakshmi"
}));
Expected output
Confirmed for Lakshmi
Tip: Remove temporary debugger statements before production deployment. They can pause execution when developer tools are open.
7. A Practical Error Investigation
Consider a booking function that displays a confirmation message. The message is missing the patient's name.
Example 14: Find the actual problem
function showConfirmation(appointment) {
console.log("Confirmed for: " + appointment.patientName);
}
const appointment = {
patient: "Ravi",
time: "11:00 AM"
};
showConfirmation(appointment);
Unexpected output
Confirmed for: undefined
The function expects patientName. The object contains patient. This is a property name mismatch, not necessarily an exception.
Corrected code
function showConfirmation(appointment) {
if (!appointment || !appointment.patient) {
throw new Error("Valid patient details are required");
}
console.log("Confirmed for: " + appointment.patient);
}
const appointment = {
patient: "Ravi",
time: "11:00 AM"
};
try {
showConfirmation(appointment);
} catch (error) {
console.error(error.message);
}
Expected output
Confirmed for: Ravi
This example shows why debugging matters. Not every defect produces an exception. Some defects produce incorrect results instead.
8. Common Mistakes and Best Practices
Mistake 1: Empty catch blocks
An empty catch block hides the failure. Always handle the error or pass it to a suitable error-reporting system.
Avoid this
try {
bookAppointment();
} catch (error) {
// The error is ignored
}
Use this instead
try {
bookAppointment();
} catch (error) {
console.error("Booking failed:", error.message);
}
Mistake 2: Forgetting to await a Promise
A rejected Promise may happen after the try block has already finished. Await the Promise inside the try block.
Avoid this
async function loadData() {
try {
fetch("/api/appointments");
} catch (error) {
console.error(error);
}
}
Use this instead
async function loadData() {
try {
const response = await fetch("/api/appointments");
if (!response.ok) throw new Error("Request failed");
return await response.json();
} catch (error) {
console.error(error.message);
throw error;
}
}
Mistake 3: Showing technical details to users
Raw stack traces and internal messages can expose implementation details. Show a friendly message to users. Keep diagnostic details in protected logs.
Mistake 4: Treating every error as the same
Validation errors, network failures, and unexpected programming errors need different responses. Handle known cases clearly. Do not hide unexpected failures.
Mistake 5: Logging sensitive information
Never log passwords, access tokens, payment details, or private patient information. Store only the information needed for diagnosis.
Best practices checklist
- Use try/catch around operations that may throw.
- Check HTTP response status after fetch.
- Use meaningful error messages and stable error codes.
- Keep error handling close to the operation that can fail.
- Use finally for cleanup, not for hiding failures.
- Log enough context to investigate a problem safely.
- Test both successful and failed execution paths.
- Do not expose internal error details to end users.
9. Error Handling in Production Applications
Production applications need more than a console message. They need useful error reporting and safe recovery.
Separate user messages from diagnostic details
A patient should see a simple message such as "We could not complete your booking. Please try again." A developer may need the error type, request identifier, and stack trace.
Use centralized error reporting
Large applications can send unexpected errors to a monitoring service. This helps teams find repeated failures across users and sessions. Protect personal information before sending diagnostic data.
Do not confuse handling with recovery
Catching an error does not automatically fix the failed operation. Decide whether to retry, ask the user to try again, use a fallback, or stop safely.
Use retries carefully
Some network failures are temporary. A retry may help. But retrying every error can make an outage worse. Use a retry limit and delay between attempts. Do not repeat a payment or booking operation unless it is safe to do so.
10. How This Topic Comes Up in Interviews
Question 1: What is the difference between throw and try/catch?
What the interviewer wants: They want to know whether you understand how exceptions travel through JavaScript.
Strong answer: "The throw statement creates an exception. The try block runs code that may fail. The catch block handles an exception when one occurs. In our hospital booking example, I throw an error when the patient name is missing. I catch it so another appointment can still be processed."
Question 2: Does fetch throw an error for HTTP 404?
Strong answer: "No. Fetch normally resolves its Promise when the server returns an HTTP response, even for 404 or 500. I check response.ok and throw an error when the response is unsuccessful. Network failures can reject the Promise, so I also use try/catch."
Question 3: What is the purpose of finally?
Strong answer: "Finally runs after the try and catch blocks finish. I use it for cleanup tasks. For example, I can stop a loading indicator after an appointment request. I avoid returning from finally because it can change normal control flow."
Question 4: How do you debug a JavaScript production issue?
Strong answer: "First, I identify the affected user flow and reproduce the issue. Then I inspect logs and error details. I check the failing line and the values passed into it. I fix the root cause and add a test for the same failure. I also check whether the fix affects other appointment flows."
What interviewers expect at each level
| Level | Expected understanding |
|---|---|
| Junior | Explain try, catch, finally, and common error types. |
| Senior | Handle asynchronous failures and design useful error responses. |
| Architect | Plan logging, monitoring, recovery, security, and failure boundaries. |
11. Hands-On Practice
Beginner: Validate a patient appointment
Create a function that accepts a patient name and appointment time.
- Throw an error when the patient name is empty.
- Throw an error when the appointment time is missing.
- Use try/catch to display a useful message.
Expected result: Valid appointments should be confirmed. Invalid appointments should show a clear error.
Intermediate: Handle an API failure
Write an async function that requests appointment data.
- Use fetch to request the data.
- Check response.ok before reading JSON.
- Handle network and HTTP errors separately where useful.
- Show a friendly message when the request fails.
Hint: Use await inside the try block. Test with an endpoint that returns a non-success status.
Advanced: Build a reusable error handler
Create an AppointmentError class with a message and error code.
- Handle missing patient details.
- Handle unavailable appointment slots.
- Keep unexpected errors separate from known business errors.
- Return safe user messages and log useful diagnostic details.
Expected result: Your application should distinguish known booking failures from unexpected programming errors.
12. Frequently Asked Questions
Can we use try/catch for every JavaScript error?
No. Try/catch handles exceptions thrown inside its execution flow. It does not automatically catch every error from unrelated asynchronous callbacks or later Promise operations.
What is the difference between an error and a bug?
An error is a problem reported during execution. A bug is a defect in the code or design. Some bugs produce errors. Others produce incorrect results without throwing exceptions.
Should we use console.error in production?
It can help during development. Production applications should use a controlled logging and monitoring approach. Avoid exposing sensitive data or relying only on the browser console.
Can finally run when an error occurs?
Yes. Finally normally runs after the try or catch block. It is useful for cleanup, even when an exception occurs.
13. Next Steps and Community
Error handling and debugging are essential skills for reliable JavaScript applications. Start by handling one failure at a time. Then learn to investigate problems with developer tools and useful logs.
Try the exercises with your own appointment examples. Share your solutions, discuss alternative approaches, and help other learners improve.
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.