Error Handling and Debugging
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Use try, catch and finally correctly.
- Create and distinguish error types.
- Handle rejections from async code and debug failures methodically.
Overview
#Errors are values you can catch
When code throws, control jumps to the nearest enclosing try block. The catch clause receives the thrown value, which is usually an Error instance. The finally clause always runs, whether or not an error was thrown, and is the place for cleanup.
try {
JSON.parse('{');
} catch (error) {
console.log(error instanceof SyntaxError); // true
} finally {
console.log('cleanup');
}
Built-in error types
SyntaxError, TypeError, ReferenceError and RangeError are the common built-ins. A TypeError means an operation was applied to the wrong kind of value. A ReferenceError means a name was not declared. Matching on the error type lets you handle specific failures and rethrow the rest.
Custom errors
Extending Error gives you a named type and a stack trace. Set the name property so logs are readable, and add any fields the caller needs, such as a status code.
Async errors
A rejected promise is not caught by a surrounding try/catch unless you await it inside that try. Unhandled rejections terminate modern runtimes. Attach a catch or await inside a try, and never leave a floating promise.
Debugging methodically
Reproduce the failure with the smallest input, read the stack trace from the top, inspect the actual values at the failure point, and change one thing at a time. Console logging and breakpoints are both valid; the discipline is to form a hypothesis and test it.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this function return?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptfunction f() { try { return 'try'; } finally { return 'finally'; } }Exercise 2Explain
Explain why the try/catch here does not catch the rejection.
starter.javascripttry { Promise.reject(new Error('boom')); } catch (error) { console.log('caught'); }Reveal the reference answer
reference.javascriptThe rejected promise settles asynchronously, after the try block has already finished. The synchronous catch cannot see a rejection that happens in a later microtask. To catch it, await the promise inside the try block, or attach a catch handler to the promise.try/catch only catches synchronous throws from the current execution. Rejections must be awaited or handled with catch.
Exercise 3Implement
Implement `safeParse(text, fallback)` that returns the parsed value or the fallback when parsing fails. Running `console.log(safeParse('{"a":1}', null).a, safeParse('{', 'bad'));` should print `1 bad`.
starter.javascriptfunction safeParse(text, fallback) { // your code here }Reveal the reference answer
reference.javascriptfunction safeParse(text, fallback) { try { return JSON.parse(text); } catch (error) { return fallback; } }Authored expected output: 1 bad
JSON.parse throws a SyntaxError on invalid input. Catching it and returning the fallback turns a crash into a predictable value, which is the right shape for parsing untrusted input.
Exercise 4Debug
This code silently swallows every error, so a real bug becomes invisible. Fix it to rethrow unexpected errors.
starter.javascriptasync function load() { try { return await fetchData(); } catch (error) { return null; } }Reveal the reference answer
reference.javascriptasync function load() { try { return await fetchData(); } catch (error) { if (error instanceof TypeError) return null; throw error; } }Returning null for every error hides programming mistakes. Narrowing the catch to the expected error type and rethrowing the rest keeps the recovery behavior while surfacing real defects.
Exercise 5Test
Write a test that proves a custom error carries its name and a status code.
starter.javascriptclass HttpError extends Error { constructor(message, status) { super(message); this.name = 'HttpError'; this.status = status; } }Reveal the reference answer
reference.javascriptconst error = new HttpError('not found', 404); if (!(error instanceof Error)) throw new Error('not an Error'); if (error.name !== 'HttpError') throw new Error('wrong name'); if (error.status !== 404) throw new Error('wrong status'); if (typeof error.stack !== 'string') throw new Error('no stack'); console.log('custom error verified');Authored expected output: custom error verified
Extending Error keeps the prototype chain and stack trace. Setting name makes logs readable, and the status field lets callers branch on the failure.
Exercise 6Interview
Describe your process for debugging a production error you cannot reproduce locally.
Reveal the reference answer
reference.javascriptFirst, gather the evidence: the stack trace, the error message, the user action, the browser and the time. Second, look for a pattern across reports, such as a shared route or input shape. Third, add targeted logging or error reporting around the suspected path and ship it behind a safe guard. Fourth, form a hypothesis and test it with a minimal reproduction. Finally, fix the root cause, add a regression test and verify in production. I avoid guessing and avoid changing multiple things at once.The answer should show a repeatable method: gather evidence, narrow scope, instrument, hypothesize, fix, test. Naming a specific tool or log field makes it concrete.
Common misconceptions
#- A try/catch around an async call catches rejections without await.
- finally runs only when no error was thrown.
- Catching an error and logging it is the same as handling it.
Follow-up practice
#- javascript-foundations-metaprogramming
- javascript-foundations-async-event-loop
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.