JavaScript · Lesson 14 of 20 · 4 min
Error Handling & Debugging
This is how you show you write resilient code and have a systematic approach to fixing it.
In an interview, you're not expected to write bug-free code on a whiteboard. You are, however, expected to know what to do when things go wrong. This is about demonstrating that you can anticipate failure points and diagnose problems methodically.
How to handle runtime failures
The try...catch statement is your primary tool for handling exceptions—unexpected errors that occur during execution. Use it for operations that can fail for reasons outside your control, like network requests or parsing external data.
Do not use try...catch for predictable logic. If you can check for a condition with an if statement, do that instead. try...catch is for the exceptional, not the expected.
The catch block receives an Error object containing name, message, and a stack trace. The stack trace is critical for debugging; always log it or send it to an error reporting service.
The trap: Catching an error and doing nothing with it (catch (e) {}). This is called "swallowing" an error. It silences a problem that will inevitably surface elsewhere, making it much harder to debug. Never do this.
An optional finally block runs after try or catch, regardless of the outcome. It is essential for cleanup tasks. If you show a loading spinner before an API call in a try block, you must hide it in the finally block. This guarantees the UI won't get stuck in a loading state if the request fails.
Why you should throw custom errors
When your own function encounters a situation it cannot handle, like invalid input, throw an error. This stops execution immediately and forces the calling code to deal with the problem. It is much clearer than returning null or an error code.
throw new Error("Invalid input") is the minimum. For more robust code, create your own error classes by extending the built-in Error class.
This gives you two advantages:
- You can add more context to the error, like which field failed validation.
- The caller can use
instanceofto identify and handle specific error types differently.
Here is how you create and use a custom error. This pattern is worth remembering for an interview.
// A custom error for validation failures
class ValidationError extends Error {
constructor(message, field) {
super(message); // Pass message to the parent Error class
this.name = "ValidationError";
this.field = field; // Add custom context
}
}
function saveUser(user) {
if (!user.name) {
throw new ValidationError("User name is required.", "name");
}
if (!user.email || !user.email.includes('@')) {
throw new ValidationError("A valid email is required.", "email");
}
// ...proceed to save the user
console.log(`Saving user: ${user.name}`);
}
try {
const user = { name: "Alice", email: "invalid-email" };
saveUser(user);
} catch (error) {
console.error(`${error.name}: ${error.message}`);
// Now we can provide specific feedback
if (error instanceof ValidationError) {
console.error(`Please correct the '${error.field}' field.`);
// In a real UI, you would use this to highlight the input field.
} else {
// Handle other unexpected errors (e.g., network, database)
console.error("An unexpected error occurred. Please try again later.");
}
}
In an interview, explaining why custom errors are useful is key. Talk about creating a clear contract for your functions and enabling targeted error handling. This shows you think about API design and maintainability.
A systematic debugging process
"How do you debug a problem?" is a common behavioral question. Avoid just saying "I use console.log." Describe a structured process.
-
Reproduce. Isolate the exact steps to trigger the bug consistently. This is the most important step. If you can't reproduce it, you can't fix it.
-
Locate. Form a hypothesis. The error's stack trace is your map, pointing to where the error was thrown. If there's no error, make an educated guess about which part of the code is responsible.
-
Inspect. Use the right tool for the job.
console.log()is fast for checking a single value at a specific point in time. It's a blunt instrument.- The debugger is a precision tool. Set a breakpoint in your browser's dev tools. This pauses execution and gives you a complete snapshot: the call stack, all variables in every scope, and the current state of the page. From here, you can step through the code line-by-line to watch how state changes and pinpoint the exact moment it becomes incorrect.
-
Fix. Once you understand the cause, implement a fix and write a test that would have caught the bug.
The debugger; statement is a programmatic breakpoint. You can add it directly to your code. When the browser's dev tools are open, execution will pause at that line. It's useful for debugging issues that are hard to catch manually, like those happening on page load or during complex UI interactions.
Try it
Take a function you've written that validates input and returns a boolean or null on failure. Refactor it to throw a custom ValidationError instead. Then, update the code that calls it to use a try...catch block to handle the error.
Next: Asynchronous JavaScript: Async/Await, where we'll see how try...catch becomes essential for handling errors in modern async code.
Lock it in — apply this lesson under interview conditions.